C++设计模式:空对象模式

一、源代码:

#include<iostream>
#include<memory>
#include<vector>

using namespace std;

class AbstractCustomer
{
public:
    virtual bool isNil() = 0;
    virtual string getName() = 0;
    virtual ~AbstractCustomer() = default;
protected:
    string _name;
};

class RealCustomer:public AbstractCustomer
{
public:
    RealCustomer(string name)
    {
        this->_name = name;
    }
    virtual string getName() override
    {
        return _name;
    }
    virtual bool isNil() override
    {
        return false;
    }
};

class NullCustomer:public AbstractCustomer
{
public:
    virtual string getName() override
    {
        return "Not Available is Customer Database";
    }
    virtual bool isNil() override
    {
        return true;
    }
};

class CustomerFactory
{
public:
    static vector<string> s_names;
    static shared_ptr<AbstractCustomer> getCustomer(string name)
    {
        for(const auto& each:s_names)
        {
            if(each==name) return make_shared<RealCustomer>(name);
        }
        return make_shared<NullCustomer>();
    }
};
vector<string> CustomerFactory::s_names = {"Rob","Joe","Julie"};

int main()
{
    shared_ptr<AbstractCustomer> customer1 = CustomerFactory::getCustomer("Rob");
    shared_ptr<AbstractCustomer> customer2 = CustomerFactory::getCustomer("Bob");
    shared_ptr<AbstractCustomer> customer3 = CustomerFactory::getCustomer("Julie");
    shared_ptr<AbstractCustomer> customer4 = CustomerFactory::getCustomer("Laura");

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


二、运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值