设计模式——空对象模式(C++实现)

空对象模式

          空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。

适用场景

       需要在无法创建具体实例或数据不可用的时候提供默认行为,则需要用空对象模式,而不是仅仅返回一个NULL值。

 

采用菜鸟教程的例子,这里用C++实现

#include<iostream>
#include<string>

using namespace std;

//创建一个抽象类AbstractCustomer。
class AbstractCustomer
{
public:
	AbstractCustomer() {};
	virtual ~AbstractCustomer() {};
	virtual bool isnull()=0;
	virtual string getName() = 0;

protected:
	string name;
};

//创建扩展了抽象类AbstractCustomer的实体类RealCustomer。
class RealCustomer :AbstractCustomer
{
public:
	RealCustomer(string tname) { name = tname; };
	~RealCustomer() {};
	bool isnull() { return false; };
	string getName() { return name; };
};

//创建扩展了抽象类AbstractCustomer的空类NullCustomer。
class NullCustomer :AbstractCustomer
{
public:
	NullCustomer() {};
	~NullCustomer() {};
	bool isnull() { return true; };
	string getName() { return "Not Available in coustomer database"; };
};

//创建CustomerFactory类,用来获取实体类或空类的实例
class CustomerFactory
{
public:
	CustomerFactory() {};
	~CustomerFactory() {};
	static string name[3];
	static AbstractCustomer* getCustomer(string tname);
};

string CustomerFactory::name[3] = { "Rob","Joe","Julie" };

AbstractCustomer* CustomerFactory::getCustomer(string tname)
{
	int i = 0;
	for (i = 0; i < 3; i++)
	{
		if (name[i] == tname)
		{
			return (AbstractCustomer*)new RealCustomer(tname);
		}
	}
	return (AbstractCustomer*)new NullCustomer();
}

int main()
{
	AbstractCustomer *c1 = CustomerFactory::getCustomer("Rob");
	AbstractCustomer *c2 = CustomerFactory::getCustomer("Mickel");
	AbstractCustomer *c3 = CustomerFactory::getCustomer("Joe");
	AbstractCustomer *c4 = CustomerFactory::getCustomer("Julie");

	cout << "Rob: " << c1->getName() << endl;
	cout << "Mickel: " << c2->getName() << endl;
	cout << "Joe: " << c3->getName() << endl;
	cout << "Juile: " << c4->getName() << endl;

	delete c1;
	c1 = NULL;

	delete c2;
	c2 = NULL;

	delete c3;
	c3 = NULL;

	delete c4;
	c4 = NULL;

	return 0;
}

在visual studio 2015上运行结果:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值