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