一、代码
#include <iostream>
#include <string>
using namespace std;
class IBase
{
public:
virtual void outdata(string message) = 0;
};
class Base :public IBase
{
public:
void outdata(string message) override
{
cout << message << endl;
}
};
class BaseCompressedDecorator :public IBase
{
IBase& refence;
public:
BaseCompressedDecorator(IBase& BaseDecorator) :refence(BaseDecorator) {};
void outdata(string message) override
{
message = message + " Compressed";
refence.outdata(message);
}
};
class EncryptionBaseDecorator :public IBase
{
IBase& refence;
public:
EncryptionBaseDecorator(IBase& BaseDecorator) :refence(BaseDecorator) {};
void outdata(string message) override
{
message = message + " Encrypted";
refence.outdata(message);
}
};
int main() {
string message = "Hello";
Base base;
BaseCompressedDecorator base2(base);
EncryptionBaseDecorator base3(base2);
base3.outdata(message);
return 0;
}
二、使用过程
- 若类Base有函数outdata输出“Hello”,想对此输出进行修饰。
- 新建Decorator类继承Base的接口IBase,在Decorator类中创建IBase的引用,这样Decorator类就可以访问Base类。
- Decorator类重写IBase的输出函数outdata,加入装饰" Compressed"之后,再调用Decorator类中Base类的函数outdata。
- 此时调用的outdata是Base的函数。
- 如此递归调用下去,实现对结果的更改。(代码示例中一共调用了三次outdata)
这样的好处是可以不用改动原有代码,实现操作的增加。
装饰者模式详解
本文深入解析装饰者模式在代码中的应用,通过实例展示如何在不修改原有代码的基础上,通过装饰者类实现对类功能的扩展。文章详细介绍了装饰者模式的实现原理,包括类的继承、接口的使用以及递归调用的过程。
1101

被折叠的 条评论
为什么被折叠?



