Java Null Object Pattern(空对象模式)
2017-09-29 01:08
489 查看
Java Null Object Pattern(空对象模式)
在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。在空对象模式中,我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类,还创建一个未对该类做任何实现的空对象类,该空对象类将无缝地使用在需要检查空值的地方。
创建一个抽象类
/** * 1. 创建一个抽象类 * @author mazaiting */ public abstract class AbstractCustomer { protected String name; public abstract boolean isNil(); public abstract String getName(); }
创建扩展了上述类的实体类。
/** * 2. 创建扩展了AbstractCustomer的实体类。 * @author mazaiting */ public class NullCustomer extends AbstractCustomer{ @Override public boolean isNil() { return true; } @Override public String getName() { return "Not Available in Customer Database"; } } /** * 2. 创建扩展了AbstractCustomer类的实体类。 * @author mazaiting */ public class RealCustomer extends AbstractCustomer{ public RealCustomer(String name) { this.name = name; } @Override public boolean isNil() { return false; } @Override public String getName() { return name; } }
创建CustomerFactory类。
/** * 3. 创建 CustomerFactory 类。 * @author mazaiting */ 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(); } }
使用 CustomerFactory,基于客户传递的名字,来获取 RealCustomer 或 NullCustomer 对象。
/** * 4. 使用 CustomerFactory,基于客户传递的名字,来获取 RealCustomer 或 NullCustomer 对象。 * @author mazaiting */ public class Client { 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()); } }
打印结果
Customers Rob Not Available in Customer Database Julie Not Available in Customer Database
4000
相关文章推荐
- Java 空对象设计模式(Null Object Pattern) 讲解
- Java 空对象设计模式(Null Object Pattern) 讲解
- 空对象模式(Null Object Pattern)
- 被遗忘的设计模式——空对象模式(Null Object Pattern)
- 被遗忘的设计模式——空对象模式(Null Object Pattern)
- 设计模式:空对象模式(Null Object Pattern)
- 设计模式:空对象模式(Null Object Pattern)
- Java Transfer Object Pattern(传输对象模式)
- C#对象为Null模式(Null Object Pattern)实例教程
- 【设计模式】空对象模式(Null Object Pattern)
- 空对象模式(Null Object Pattern)
- 被遗忘的设计模式——空对象模式(Null Object Pattern)
- 设计模式:空对象模式(Null Object Pattern)
- 用最简单的例子理解对象为Null模式(Null Object Pattern)
- java 创建对象模式 (五种)
- Java设计模式二十一:桥模式(Bridge Pattern)
- Java之命令模式(Command Pattern)
- java设计模式---Prototype Pattern---原型模式(复制建立对象)
- java设计模式——装饰模式(Decorator Pattern)
- 深入JVM 原理(二)Java对象访问模式