今天学习了下装饰模式,亲自用C++实现了下,感觉最大的好处在于各个装饰器可以灵活的组合。UML图如下:
代码实现如下:
/*
测试装饰模式实现方法
*/
#include <iostream>
#include <string>
using namespace std;
/*
基类接口
*/
class Component
{
public:
virtual void operation(const string& msg) = 0;
};
/*
核心业务
*/
class ConcreteComponent : public Component
{
public:
void operation(const string& msg)
{
cout << "I am contrete work." << endl;
return;
}
};
/*
装饰器基类
*/
class Decorator : public Component
{
private:
Component* com;
public:
Decorator(Component* c):com(c){}
public:
void operation(const string& msg)
{
com->operation(msg);
}
};
/*
实际装饰类
*/
class Checker : public Decorator
{
public:
Checker(Component* c): Decorator(c){}
public:
void operation(const string& msg)
{
cout << "do check operations..." << endl;
Decorator::operation(msg);
}
};
/*
实际装饰类
*/
class Logger : public Decorator
{
public:
Logger(Component* c) : Decorator(c){}
public:
void operation(const string & msg)
{
cout << "do loggs..." << endl;
Decorator::operation(msg);
}
};
int main(int argc, char** argv)
{
/*
将不同的装饰类灵活的组合在一起,形成不同的功能
check-log-operation组合
*/
Component* op = new Checker(new Logger(new ConcreteComponent()));
op->operation("This is a test!");
cout << endl;
/*
log-check-operation组合
*/
Component* op1 = new Logger(new Checker(new ConcreteComponent()));
op1->operation("This is a test 2!");
return 0;
}