C++ 设计模式 装饰模式
在结构型模式中装饰模式给我留下了深刻的印象,其中也感觉到在设计模式中基本都是
依赖C++的多态来实现,装饰模式也不例外,他允许在不改变原有类的代码的基础上,
不通过直接继承原有类的代码通过一个抽象接口层进行实现,甚至可以随意的组合,
所以这里记录之以备使用
下面是模型图:
下面是一个简单的模拟代码,模拟本来一个工具只有写功能,但是我们要不断的扩充其
功能让它有听有读的功能:
这是跑出来的结果
—-source tool—-
i can write!!
—–can listen tool—–
i can write!!
i can listene !!
—-can read tool——
i can write!!
i can read !!
—-can listen and read tool——
i can write!!
i can read !!
i can listene !!
下面是代码:
点击(此处)折叠或打开
- #include <iostream>
- using namespace std;
- /*装饰模式
- *装饰者模式(Decorator Pattern)动态的给一个对象添加一些额外的职责
- */
- class ABS_TOOL
- {
- public:
- virtual ~ABS_TOOL(){}
- virtual void fun() = 0; //功能接口
- };
- class write:public ABS_TOOL
- {
- public:
- virtual void fun()
- {
- cout<<“i can write!!n”;
- }
- };
- class listen:public ABS_TOOL //继承
- {
- public:
- virtual ~listen(){}
- listen(ABS_TOOL* tool) //依赖
- {
- this–>tool = tool;
- }
- virtual void fun()
- {
- tool–>fun();
- cout<<“i can listene !!n”;
- }
- private:
- ABS_TOOL* tool; //聚合
- };
- class read:public ABS_TOOL //继承
- {
- public:
- virtual ~read(){}
- read(ABS_TOOL* tool) //依赖
- {
- this–>tool = tool;
- }
- virtual void fun()
- {
- tool–>fun();
- cout<<“i can read !!n”;
- }
- private:
- ABS_TOOL* tool; //聚合
- };
- int main(void)
- {
- cout<<“—-source tool—-n”;
- write test1;
- test1.fun();
- cout<<“—–can listen tool—–n”;
- listen test2(&test1);
- test2.fun();
- cout<<“—-can read tool——n”;
- read test3(&test1);
- test3.fun();
- cout<<“—-can listen and read tool——n”;
- listen test4(&test3);
- test4.fun();
- return 0;
- }
作者微信:
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7728585/viewspace-2137337/,如需转载,请注明出处,否则将追究法律责任。
主题测试文章,只做测试使用。发布者:深沉的少年,转转请注明出处:http://www.cxybcw.com/183833.html