当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 设计模式系列 - 空对象模式

设计模式系列 - 空对象模式

2019年01月07日  | 移动技术网IT编程  | 我要评论

空对象模式取代简单的 null 值判断,将空值检查作为一种不做任何事情的行为。

介绍

在空对象模式中,我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类,还创建一个未对该类做任何实现的空对象类,该空对象类将无缝地使用在需要检查空值的地方。

类图描述

代码实现

1、定义抽象类

    public abstract class abstractcustomer
    {
        protected string name;
        public abstract bool isnil();
        public abstract string getname();
    }

2、定义实体类

public class nullcustomer : abstractcustomer
{
    public override string getname()
    {
        return "not available in customer database";
    }

    public override bool isnil()
    {
        return true;
    }
}

public class realcustomer : abstractcustomer
{
    public realcustomer(string name)
    {
        name = name;
    }
    public override string getname()
    {
        return this.name;
    }

    public override bool isnil()
    {
        return false;
    }
}

3、定义工厂类

public class customerfactory
{
    public static readonly string[] names = { "rob", "joe", "julie" };

    public static abstractcustomer getcustomer(string name)
    {
        for (int i = 0; i < names.length; i++)
        {
            if (names[i] == name)
                return new realcustomer(names[i]);
        }
        return new nullcustomer();
    }
}

4、上层调用

class program
{
    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.readkey();
    }
}

总结

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网