模式的定义
空对象模式(Null Object Pattern)定义如下:
Provide an object as a surrogate for the lack of an object of a given type. The Null Object provides intelligent do nothing behavior, hiding the details from its collaborators.
UML类图
20161117124923108.png模式的简单实现:
先定义一个AbstractObject类:
/**
* 抽象类
*/
public abstract class AbstractObject {
public int id;
public String name;
//抽象方法
public abstract void doAction();
public abstract boolean isNull();
}
再定义一个实现类:ConcreteObject
public class ConcreteObject extends AbstractObject {
public ConcreteObject(int id,String name) {
super.id = id;
super.name = name;
}
@Override
public void doAction() {
System.out.println("id:"+id+"--name:"+name+"---doAction()");
}
@Override
public boolean isNull() {
return false;
}
}
我们再定义一个工厂方法类:ObjectFactory
/**
* 生成对象
*/
public class ObjectFactory {
public static AbstractObject creator(int id) {
AbstractObject result = null;
switch (id) {
case 1:
result = new ConcreteObject(1, "hello");
break;
case 2:
result = new ConcreteObject(2, "world");
break;
default:
result = new NullObject();
break;
}
return result;
}
}
客户端如下调用即可:
public class Main {
public static void main(String[] args) {
AbstractObject aObject = ObjectFactory.creator(1);
aObject.doAction();
System.out.println("----------------------------");
aObject = ObjectFactory.creator(2);
aObject.doAction();
System.out.println("----------------------------");
aObject = ObjectFactory.creator(-1);
System.out.println("is null"+aObject.isNull());
aObject.doAction();
System.out.println("----------------------------");
}
}
而在没有采用此方式的情况下,我们需要在每次创建的时候做判空处理。
网友评论