Decorator装饰器模式(C++)

本文深入探讨装饰者模式,一种允许在不改变原有组件的情况下增加其功能的设计模式。通过具体实例,展示如何为文章添加页眉和页脚,以及模式背后的原理和潜在的存储空间问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


例如:一篇文章本身无需知道自己的页首和页脚;使用者可以很方便的添加不同的页眉与页脚
对比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。

 

### C++装饰器模式的实现与用法 #### 什么是装饰器模式装饰器模式是一种结构型设计模式,用于在不改变对象原有结构的前提下为其动态添加新功能。这种方式避免了通过继承来扩展功能可能引发的类层次复杂化问题[^2]。 #### 装饰器模式的核心概念 装饰器模式主要由以下几个部分构成: 1. **抽象组件(Component)**:定义对象的接口,所有具体组件和装饰器都需实现此接口。 2. **具体组件(Concrete Component)**:实现了抽象组件中的方法。 3. **装饰器抽象类(Decorator)**:持有一个指向抽象组件的对象,并定义了一个与抽象组件一致的接口。 4. **具体装饰器(Concrete Decorator)**:负责向组件添加职责或修改其行为。 #### C++装饰器模式的实现步骤 以下是装饰器模式的一个典型实现流程: 1. 定义一个抽象基类 `Component`,其中包含需要被增强的方法声明。 2. 创建具体的组件类 `ConcreteComponent` 并实现上述方法。 3. 设计一个装饰器基类 `BaseDecorator`,持有对 `Component` 的引用并重载相同的方法。 4. 构建多个具体装饰器类 `ConcreteDecoratorA`, `ConcreteDecoratorB` 等,在这些类中可以增加额外的行为逻辑。 下面是一个完整的C++示例代码展示如何应用装饰器模式: ```cpp #include <iostream> #include <memory> // 抽象组件 (Component) class Beverage { public: virtual ~Beverage() {} virtual std::string getDescription() const = 0; virtual double cost() const = 0; }; // 具体组件 (Concrete Component): 咖啡 class Espresso : public Beverage { public: std::string getDescription() const override { return "Espresso"; } double cost() const override { return 1.99; } }; // 装饰器抽象类 (Decorator) class CondimentDecorator : public Beverage { protected: std::shared_ptr<Beverage> beverage; public: explicit CondimentDecorator(std::shared_ptr<Beverage> b) : beverage(b) {} std::string getDescription() const override { return beverage->getDescription(); } // 默认返回原描述 }; // 具体装饰器 A: 加牛奶 class Milk : public CondimentDecorator { public: using CondimentDecorator::CondimentDecorator; std::string getDescription() const override { return beverage->getDescription() + ", Milk"; } double cost() const override { return beverage->cost() + 0.5; // 添加费用 } }; // 具体装饰器 B: 加摩卡 class Mocha : public CondimentDecorator { public: using CondimentDecorator::CondimentDecorator; std::string getDescription() const override { return beverage->getDescription() + ", Mocha"; } double cost() const override { return beverage->cost() + 0.7; // 添加费用 } }; int main() { auto espresso = std::make_shared<Espresso>(); std::cout << espresso->getDescription() << ": $" << espresso->cost() << "\n"; auto mochaDecorated = std::make_shared<Mocha>(espresso); auto milkMochaDecorated = std::make_shared<Milk>(mochaDecorated); std::cout << milkMochaDecorated->getDescription() << ": $" << milkMochaDecorated->cost() << "\n"; return 0; } ``` 在这个例子中,我们展示了如何使用装饰器模式逐步为一杯咖啡添加不同的调料(如牛奶和摩卡),同时保持原有的核心业务逻辑不变[^3]。 #### 关键特性总结 - 动态扩展能力:无需更改已有代码即可新增功能。 - 遵循开闭原则:模块对外部封闭修改,对内部开放扩展。 - 减少子类数量:相比传统继承方式更加灵活高效[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值