实例
我们将创建一个定义外观的AbstractCustomer抽象类。这里的客户名称和扩展AbstractCustomer类的具体类。创建工厂类CustomerFactory以根据传递给它的客户名称返回RealCustomer或NullCustomer对象。
我们的演示类NullPatternDemo将使用CustomerFactory演示Null Object模式的使用。
第1步 - 创建一个抽象类。 AbstractCustomer.java
public abstract class AbstractCustomer {
protected String name;
public abstract boolean isNil();
public abstract String getName();
}
第2步 - 创建扩展上述类的具体类。 RealCustomer.java , NullCustomer.java
public class RealCustomer extends AbstractCustomer {
public RealCustomer(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isNil() {
return false;
}
}
public class NullCustomer extends AbstractCustomer {
@Override
public String getName() {
return "Not Available in Customer Database";
}
@Override
public boolean isNil() {
return true;
}
}
第3步 - 创建CustomerFactory类。 CustomerFactory.java
public class CustomerFactory {
public static final String[] names = {"Rob", "Joe", "Julie"};
public static AbstractCustomer getCustomer(String name){
for (int i = 0; i < names.length; i++) {
if (names[i].equalsIgnoreCase(name)){
return new RealCustomer(name);
}
}
return new NullCustomer();
}
}
步骤4 - 使用CustomerFactory根据传递给它的客户名称获取RealCustomer或NullCustomer对象。 NullPatternDemo.java
public class NullPatternDemo {
public static void main(String[] args) {
AbstractCustomer customer1 = CustomerFactory.getCustomer("Rob");
AbstractCustomer customer2 = CustomerFactory.getCustomer("Bob");
AbstractCustomer customer3 = CustomerFactory.getCustomer("Julie");
AbstractCustomer customer4 = CustomerFactory.getCustomer("Laura");
System.out.println("Customers");
System.out.println(customer1.getName());
System.out.println(customer2.getName());
System.out.println(customer3.getName());
System.out.println(customer4.getName());
}
}
第5步 - 验证输出。
Customers
Rob
Not Available in Customer Database
Julie
Not Available in Customer Database