Decorator装饰器模式(C++)

简而言之,它提供了一种对被装饰者透明的方法;


例如:一篇文章本身无需知道自己的页首和页脚;使用者可以很方便的添加不同的页眉与页脚
对比Strategy模式:对象需要知道使用的是哪个算法,该方式对组件不可见,但是调用者可以任意数量添加装饰。

不足:每次装饰都会引入一个新的小对象,即使每次生成的组件类似,仍每次都新创建装饰器,会占用许多额外的存储空间。

 

如图,为具体的组建添加DecA与DecB装饰

 

实战:实现一个为卷子添加页眉、页脚的简单程序

效果:

header 2015 is added.
header 'Final Test' is added.
Final test starts!
footer 1 is added.

 关键语句:

WhitePaper* wp = new FooterDecorator(new HeaderDecorator(new TestPaper, "'Final Test'"),"2015"));

其中WhitePaper为整个装饰模式中的父类 ,TestPaper为实例对象,使用Footer和Header来添加装饰

#include <cstdio>
//#include<crtdbg.h>
using namespace std;

/*Decorator模式: BaseClass=WhitePaper*/

class WhitePaper {
public:
	virtual ~WhitePaper() {};
	virtual void PrintContents();
};
void WhitePaper::PrintContents() {
	printf("This is a white paper.\n");
}

/*各种装饰器的共同父类*/
class Decorator : public WhitePaper {
public:
	Decorator(WhitePaper *);
	virtual ~Decorator() { delete _wPaper; }; //!!!!!!!!!!!!
	virtual void PrintContents();
private:
	WhitePaper *_wPaper;
};
Decorator::Decorator(WhitePaper* pw) {
	_wPaper = pw;
	printf("Decorator constructed.\n");
}

void Decorator::PrintContents() {
	_wPaper->PrintContents();
}
/*页眉装饰器*/
class HeaderDecorator : public Decorator {
public:
	HeaderDecorator(WhitePaper*, const char* str);
	~HeaderDecorator() {};
	virtual void PrintContents();
private:
	const char* s;
};
HeaderDecorator::HeaderDecorator(WhitePaper* pw, const char* str):Decorator(pw){
	printf("Header %s constructed.\n", str);
	s = str;
}

void HeaderDecorator::PrintContents() {
	printf("header %s is added.\n", this->s);
	Decorator::PrintContents();
}
/*页脚装饰器*/
class FooterDecorator : public Decorator {
public:
	FooterDecorator(WhitePaper*, int n);
	~FooterDecorator() {};
	virtual void PrintContents();
private:
	int _n;
};
FooterDecorator::FooterDecorator(WhitePaper* pw, int n) :Decorator(pw) {
	printf("Foot constructed.\n");
	_n = n;
}
void FooterDecorator::PrintContents() {
	Decorator::PrintContents();
	printf("footer %d is added.\n", this->_n);
}

/*实体类*/
class TestPaper : public WhitePaper{
public:
	void PrintContents();
};
void TestPaper::PrintContents() {
	printf("Final test starts!\n");
}

int main() {
	WhitePaper* wp = new TestPaper;
	wp = new FooterDecorator(new HeaderDecorator(new HeaderDecorator(wp, "'Final Test'"), "2015"),1);
	wp->PrintContents();
	delete wp;
	getchar();
	//_CrtDumpMemoryLeaks(); //检测内存溢出
	return 0;
}

 

附:与堆内存有关的杂谈

使用父类指针释放子类对象时,父类的析构函数一定要是virtual的!!

如图:

黑点为基类指针,V-Table表示类的虚函数表。若未声明为virtual,则DecB的绿色部分和黑色部分被释放,子类成员内存泄漏。声明为virtual后析构函数被覆盖,这样调用的才是正确的版本。

从上面的内存情况同时可以看出,如果对pBase不作处理,则第一个实体和第二个实体仍然会阴魂不散,因为我们丢失了所有访问它们的渠道。故Decorator的析构函数中对pBase指向的内容一定不能忘记调用delete。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值