您好,登录后才能下订单哦!
这篇文章主要介绍“C++装饰模式怎么使用”,在日常操作中,相信很多人在C++装饰模式怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++装饰模式怎么使用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
															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;
}
到此,关于“C++装饰模式怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。