一、源代码:
#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;
}
二、运行结果:

本文介绍了一种使用C++实现的工厂模式和空对象模式的代码示例,通过创建客户类的工厂来返回真实客户或空客户对象,有效地区分了客户是否存在的情况。代码展示了如何通过继承和多态实现这一设计模式,以及如何在主函数中调用工厂方法获取不同类型的客户实例。
523

被折叠的 条评论
为什么被折叠?



