空对象模式
内容参考 w3cschool
分类:行为型设计模式
应用:类似于一张临时出入卡
目录
UML类图
创建顾客抽象类
public abstract class AbstractCustomer {
protected String name;
/**
* 判断是否为空
* @return 布尔值
*/
public abstract Boolean isNull();
/**
* 获取名字
* @return 名字的字符串
*/
public abstract String getName();
}
创建 存在的顾客以及不存在的顾客
RealCustomer
public class RealCustomer extends AbstractCustomer{
public RealCustomer(String name) {
this.name = name;
}
@Override
public Boolean isNull() {
return false;
}
@Override
public String getName() {
return name;
}
}
NullCustomer
public class NullCustomer extends AbstractCustomer{
@Override
public Boolean isNull() {
return true;
}
@Override
public String getName() {
return "[Null Object]";
}
}
创建CustomerFactory
public class CustomerFactory {
public static final String[] names = {"Dcpnet00","Dcpnet01","Dcpnet02"};
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();
}
}
运行测试
public class ExecuteMain {
public static void main(String[] args) {
AbstractCustomer customer1 = CustomerFactory.getCustomer("Dcpnet00");
AbstractCustomer customer2 = CustomerFactory.getCustomer("Dcpnet01");
AbstractCustomer customer3 = CustomerFactory.getCustomer("Dcpnet02");
AbstractCustomer customer4 = CustomerFactory.getCustomer("Dcpnet03");
System.out.println("-------Customers--------");
System.out.println(customer1.getName());
System.out.println(customer2.getName());
System.out.println(customer3.getName());
System.out.println(customer4.getName());
}
}
-------Customers--------
Dcpnet00
Dcpnet01
Dcpnet02
[Null Object]
Process finished with exit code 0