【设计模式】空对象模式
2023-09-14 09:00:42 时间
在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
在空对象模式中,我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类,还创建一个未对该类做任何实现的空对象类,该空对象类将无缝地使用在需要检查空值的地方。
实现
我们将创建一个定义操作(在这里,是客户的名称)的 AbstractCustomer 抽象类,和扩展了 AbstractCustomer 类的实体类。工厂类CustomerFactory 基于客户传递的名字来返回 RealCustomer 或 NullCustomer 对象。
NullPatternDemo,我们的演示类使用 CustomerFactory 来演示空对象模式的用法。
步骤 1
创建一个抽象类。
public abstract class AbstractCustomer { protected String name; public abstract boolean isNil(); public abstract String getName(); }
步骤 2
创建扩展了上述类的实体类。
public class RealCustomer extends AbstractCustomer { public RealCustomer(String name) { this.name = name; } @Override public String getName() { return name; } @Override public boolean isNil() { return false; } }
public class NullCustomer extends AbstractCustomer { @Override public String getName() { return "Not Available in Customer Database"; } @Override public boolean isNil() { return true; } }
步骤 3
创建 CustomerFactory 类。
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(); } }
步骤 4
使用 CustomerFactory,基于客户传递的名字,来获取 RealCustomer 或 NullCustomer 对象。
public class NullPatternDemo { 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()); } }
步骤 5
验证输出。
Customers
Rob
Not Available in Customer Database
Julie
Not Available in Customer Database
相关文章
- Kubernetes 系列(三):剖析Pod对象
- 设计模式 ( 二十 ) 访问者模式Visitor(对象行为型)
- 设计模式 ( 十八 ) 策略模式Strategy(对象行为型)
- 设计模式 ( 十二 ) 职责链模式(Chain of Responsibility)(对象行为)
- 【设计模式】传输对象模式
- .NET Core采用的全新配置系统[4]: “Options模式”下各种类型的Options对象是如何绑定的?
- Atitit 遍历 与循环模式大总结 目录 1.1. 遍历的对象 数组 或对象 或对象数组1 2. 遍历的概念2 2.1. 祖先后代同胞 过滤2 3. 常见的遍历四种方式2 3.1.
- java对象和json对象之间互相转换
- Java代理模式:如何优雅地控制对象访问?
- PHP面试题:单例模式,创建mysqli数据库链接的单例对象
- 〖Python WEB 自动化测试实战篇⑫〗- 实战 - PageObject框架设计(亦叫做 “页面对象” 模式)
- 【Groovy】MOP 元对象协议与元编程 ( 方法委托 | 使用 @Delegate 注解进行方法委托 )
- 设计模式 ( 十八 ) 策略模式Strategy(对象行为型)
- TreeSet排序,存储自己定义对象,自己定义比較器演示样例
- 60集Python入门视频PPT整理 | Python对象类型及其运算
- LabVIEW中前面板的对象为什么是分别更新的?
- 数据访问对象模式
- python基础===文件对象的访问模式,以及计数循环的使用方法
- Java组合模式:如何通过对象组合实现更高效的代码设计
- 从零开始构建Java对象:探究建造者模式的设计之美
- JavaScript 方法、对象