设计模式【空对象模式NullObjectPattern】
2017-10-22 16:27
489 查看
空对象模式
在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。在空对象模式中,我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类,还创建一个未对该类做任何实现的空对象类,该空对象类将无缝地使用在需要检查空值的地方。
实现
我们将创建一个定义操作(在这里,是客户的名称)的 AbstractCustomer 抽象类,和扩展了 AbstractCustomer 类的实体类。工厂类 CustomerFactory 基于客户传递的名字来返回 RealCustomer 或 NullCustomer 对象。NullPatternDemo,我们的演示类使用 CustomerFactory 来演示空对象模式的用法。
步骤 1
创建一个抽象类。AbstractCustomer.cs
namespace NullObjectPattern { abstract class AbstractCustomer { protected string name; public abstract bool isNull(); public abstract string getName(); } }
步骤 2
创建扩展了上述类的实体类。RealCustomer.cs
namespace NullObjectPattern { class RealCustomer : AbstractCustomer { public RealCustomer(string name) { this.name = name; } public override string getName() { return name; } public override bool isNull() { return false; ; } } }
NullCustomer.cs
namespace NullObjectPattern { class NullCustomer : AbstractCustomer { public override bool isNull() { return true; } public override string getName() { return "Not Available in Customer Database"; } } }
步骤 3
创建 CustomerFactory 类。CustomerFactory.cs
namespace NullObjectPattern { class CustomerFactory { public static string[] names = {"Rob", "Joe", "Julie"}; public static AbstractCustomer getCustomer(string name) { for (int i = 0; i < names.Length; i++) { if (names[i].Equals(name)) return new RealCustomer(name); } return new NullCustomer(); } } }
步骤 4
使用 CustomerFactory,基于客户传递的名字,来获取 RealCustomer 或 NullCustomer 对象。NullPatternDemo.cs
using System; namespace NullObjectPattern { class NullPatternDemo { 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"); Console.WriteLine("Customers"); Console.WriteLine(customer1.getName()); Console.WriteLine(customer2.getName()); Console.WriteLine(customer3.getName()); Console.WriteLine(customer4.getName()); Console.Read(); } } }
步骤 5
验证输出。Customers Rob Not Available in Customer Database Julie Not Available in Customer Database
相关文章推荐
- 设计模式之空对象模式--- Pattern Null Object
- 设计模式学习—传输对象模式(Transfer Object Design Pattern)
- 设计模式 一 值对象模式(The Value Object Pattern)
- 【设计模式】传输对象模式(Transfer Object Pattern)
- 设计模式- 主动对象(Active Object)
- 设计模式——创建型之使用建造者模式(Builder Pattern)灵活自由创建你的对象(一)
- 设计模式- 主动对象(Active Object)
- 设计模式:空对象模式(Null Object Pattern)
- 主动对象模式(Active Object pattern)
- java设计模式进阶_null-object
- Groovy 设计模式 -- null对象模式
- 【CDP-云设计模式】第6章,3.直接对象上传模式(Direct Object Upload Pattern)
- 面向对象设计模式之---建造者模式(Builder Pattern)
- Object Null 设计模式
- 面向对象设计模式之---观察者模式(Observer Pattern)
- immutable Object 不可变对象设计模式
- 【初学设计模式】Object Adapter (对象适配器)
- Java 空对象设计模式(Null Object Pattern) 讲解
- 用最简单的例子理解对象为Null模式(Null Object Pattern)
- C#对象为Null模式(Null Object Pattern)实例教程