空对象模式:属于行为型模式
基本原理:用一个空对象取代 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;
}