日期:2014-05-18  浏览次数:20896 次

Null Object Design Pattern Example in C#

Null checks are quite common in the code I write. It litters up my class methods with all kinds of exception handling. The?Null Object Design Pattern?helps me to avoid this checking for null. It provides a non functional object to the client instead of null. So I can call a method on this object that effectively does nothing. This is what I learned.

Create a base class (or interface) with an embedded null object, returning default value on null from a static read only property. Create a few objects derived from that base class and implement the abstract properties and methods. From your Repository return the Null Object instead of null whenever needed. In the example the Null Object gets returned on a find to the ‘Restless’ Person.

using System;

namespace NullObject
{
    class Program
    {
        static void Main(string[] args)
        {
            PersonRepository personRepository = new PersonRepository();