什么是空对象模式?
在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
在空对象模式中,我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类,还创建一个未对该类做任何实现的空对象类,该空对象类将无缝地使用在需要检查空值的地方。
优点:使用对象时候无需检查空值做特殊处理
缺点:使用时不知道是空值,如果接口类的需要使用异常等则不能使用 2 增加了类,增加了结构和层次的复杂性。
如何实现?
public abstract class AbstractCustomer {
protected String name;
public abstract String getName();
public abstract boolean isNull();
}
public class RealCustomer extends AbstractCustomer {
public RealCustomer(String name){
this.name = name;
}
public boolean isNull() {
return false;
}
public String getName() {
return this.name;
}
}
public class NullCustomer extends AbstractCustomer {
@Override
public String getName() {
return "this is a null object";
}
@Override
public boolean isNull() {
return true;
}
}
public class CustomerFactory {
public static AbstractCustomer getCustomer(String tempName){
String[] userName = {"张三","李四","lisa"};
for (String name: userName ) {
if(name.equalsIgnoreCase(tempName)){
return new RealCustomer(name);
}
}
return new NullCustomer();
}
}
public class Client {
public static void main(String[] args){
AbstractCustomer customer1 = CustomerFactory.getCustomer("张三");
System.out.println(customer1.getName());
AbstractCustomer customer2 = CustomerFactory.getCustomer("lisa");
System.out.println(customer2.getName());
AbstractCustomer customer3 = CustomerFactory.getCustomer("李四");
System.out.println(customer3.getName());
AbstractCustomer customer4 = CustomerFactory.getCustomer("wpz");
System.out.println(customer4.getName());
}
}