空对象模式
在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
在空对象模式中,我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类,还创建一个未对该类做任何实现的空对象类,该空对象类将无缝地使用在需要检查空值的地方。
示例演示:
- 新建一个people的抽象类 - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10- package test.nullObject; 
 public abstract class People {
 protected String name;
 public abstract boolean isNull();
 public abstract String getName();
 }
- 分别创建两个对象,一个存在的,一个不存在的 - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18- package test.nullObject; 
 public class RealPeople extends People {
 public RealPeople(String name) {
 this.name = name;
 }
 
 public boolean isNull() {
 return false;
 }
 
 public String getName() {
 return name;
 }
 }- 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14- package test.nullObject; 
 public class NullPeople extends People{
 
 public boolean isNull() {
 return true;
 }
 
 public String getName() {
 return "non-existent";
 }
 }
- 完成上述步骤,我们就可以开始演示了 - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26- package test.nullObject; 
 public class NullDemo {
 public static String[] names = {"a", "b", "c"};
 public static People getPeople(String name) {
 for (int i=0;i<names.length;i++) {
 if(names[i].equalsIgnoreCase(name)){
 return new RealPeople(name);
 }
 }
 return new NullPeople();
 }
 public static void main(String[] args) {
 People a = getPeople("a");
 People b = getPeople("b");
 People c = getPeople("c");
 People d = getPeople("d");
 System.out.println(a.getName());
 System.out.println(b.getName());
 System.out.println(c.getName());
 System.out.println(d.getName());
 }
 }- 运行结果: - 1 
 2
 3
 4- a 
 b
 c
 non-existent
说明:
空对象模式就是对于不存在的值,单独进行封装,如果返回为null,我们在最开始就做好null值的处理。