设计模式--空对象模式

空对象模式:属于行为型模式
基本原理:用一个空对象取代 NULL 对象实例的检查
主要流程:
            1.创建一个基类
            2.在这个基类上实例化一个该类型的空对象
            3.在使用时没有找到可实例化的对象,返回该对象的空对象
注意:空对象不是检查空值,而是反应一个不做任何动作的关系。这样的空对象也可以在数据不可用的时候提供默认的行为。

#include <iostream>
#include <string>
using namespace std;

//创建一个基类
class AbstractCustomer
{
protected:
    string name;
public:
    virtual bool isNil() = 0;
    virtual string getName()=0;
};
//基类的普通实例化对象
class RealCustomer : public AbstractCustomer
{
public:
    RealCustomer(string name)
    {
        this->name = name;
    }
    string getName()
    {
        return this->name;
    }
    bool isNil()
    {
        return false;
    }
};
//基类的空对象
class NullCustomer : public AbstractCustomer
{
public:
    string getName()
    {
        return this->name;
    }
    bool isNil()
    {
        return false;
    }
};
//使用工程模式创建对象
class CustomerFactory
{
public:
    string names[10] = {"Rob", "Joe", "Julie"};
    //实例化对象
    AbstractCustomer *getCustomer(string name)
    {
        for(int i=0; i < this->names->size(); ++i)
        {
            if(names[i] == name)//如果有可实例化的对象,实例化并返回
            {
                return new RealCustomer(name);
            }
        }
        //没有可实例化的对象,返回空对象
        return new NullCustomer();
    }
};
int main()
{
    CustomerFactory *customerFactory = new CustomerFactory();
    AbstractCustomer *customer1 = customerFactory->getCustomer("Rob");
    AbstractCustomer *customer2 = customerFactory->getCustomer("Bob");
    AbstractCustomer *customer3 = customerFactory->getCustomer("Julie");
    AbstractCustomer *customer4 = customerFactory->getCustomer("Laura");

    cout<<"Customers : "<<endl;
    cout<<customer1->getName()<<endl;
    cout<<customer2->getName()<<endl;
    cout<<customer3->getName()<<endl;
    cout<<customer4->getName()<<endl;

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值