空对象模式
在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
在空对象模式中,我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类,还创建一个未对该类做任何实现的空对象类,该空对象类将无缝地使用在需要检查空值的地方。
本文福利,莬费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,C++设计模式,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击莬费领取↓↓
使用场景
避免在程序中频繁出现的null值做判断。
优缺点
优点:
使用对象时无需检查空值做特殊处理。
缺点:
1、使用时不知道是空值,如果接口类的需要使用异常等则不能使用。
2、增加了类,增加了结构和层次的复杂性。
注意事项
如果只是为了避免null的出现,那请不要使用空对象模式。
UML结构图
代码实现
interface.h
创建抽象类 - 客户;创建实体类 - 真实客户、空客户
#include <string>
#include <iostream>
using namespace std;
class AbstractCustomer //基类-抽象客户
{
public:
AbstractCustomer() {}
virtual ~AbstractCustomer() {}
virtual bool isNull() = 0;
virtual string getName() = 0;
protected:
string name;
};
class RealCustomer: public AbstractCustomer //子类-真实客户
{
public:
RealCustomer(string name)
{
this->name = name;
}
string getName() { return this->name; }
bool isNull() { return false; }
};
class NullCustomer: public AbstractCustomer //子类-空客户
{
public:
string getName() { return "Not Available in Customer Database";
bool isNull() { return true; }
};
customerfactory.h
创建客户,如果存在创建真实客户,不存在创建空客户
#include "interface.h"
#include <vector>
class CustomerFactory
{
public:
std::vector<string> vec;
AbstractCustomer * getCustomer(string name) {
for (auto it : vec)
{
if (it == name)
{
return new RealCustomer(name);
}
}
return new NullCustomer();
}
};
main.cpp
实例应用 - 用空对象代替了null
#include "customerfactory.h"
int main()
{
CustomerFactory customerFactory;
customerFactory.vec.push_back("Billy");
customerFactory.vec.push_back("Kitty");
customerFactory.vec.push_back("Alice");
customerFactory.vec.push_back("Miss");
AbstractCustomer *customer1 = customerFactory.getCustomer("Billy");
AbstractCustomer *customer2 = customerFactory.getCustomer("Kitty");
AbstractCustomer *customer3 = customerFactory.getCustomer("Alice");
AbstractCustomer *customer4 = customerFactory.getCustomer("Miss");
AbstractCustomer *customer5 = customerFactory.getCustomer("Jason");
cout << "Customers:" << endl;
cout << customer1->getName() << endl;
cout << customer2->getName() << endl;
cout << customer3->getName() << endl;
cout << customer4->getName() << endl;
cout << customer5->getName() << endl;
return 0;
}
运行结果:
Customers:
Billy
Kitty
Alice
Miss
Not Available in Customer Database
本文福利,莬费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,C++设计模式,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击莬费领取↓↓