装饰模式和适配器模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰模式和适配器模式相关的知识,希望对你有一定的参考价值。
1、装饰模式
动态的给一个对象添加一些额外的职责;
侧重于功能的扩展:对其功能可以自由的增加或者减少;
2、具体实现
(1)、代码实现
#include<iostream> using namespace std; class Car{ public: virtual void show() = 0; private: }; class RunCar : public Car{ public: virtual void show(){ cout<<"可以跑"<<endl; } private: }; class SwimCarDriver : public Car{ public: SwimCarDriver(Car *car){ m_car = car; } virtual void show(){ m_car->show(); cout<<"可以游泳"<<endl; } private: Car *m_car; }; class FlyCarDriver : public Car{ public: FlyCarDriver(Car *car){{ m_car = car; } virtual void show(){ m_car->show(); cout<<"可以飞"<<endl; } private: Car *m_car; }; //功能可以自由自在的组合,功能很强大!!! int main(void){ Car *mycar = NULL; mycar = new RunCar; mycar->show(); cout<<"--------------------------------"<<endl; FlyCarDriver *flycar = new FlyCarDriver(mycar); flycar->show(); cout<<"--------------------------------"<<endl; SwimCarDriver *swimcar = new SwimCarDriver(flycar); swimcar->show(); return 0; }
3、适配器模式
适配器是将2个不同的对象进行连接和组合!
将一个类的接口转换成客户希望的另外一个接口,
4、具体实现
(1)、代码如下
#include<iostream> using namespace std; class Current18{ public: virtual void useCurrent18() = 0; private: }; class Current220{ public: void useCurrent220(){ cout<<"我是220V,欢迎使用"<<endl; } private: }; class Adapter : public Current18 { //适配器,要满足客户的需求; public: Adapter(Current220 *current){ m_current = current; } virtual void useCurrent18(){ cout<<"适配器 适配220V"<<endl; m_current->useCurrent220(); } private: Current220 *m_current; }; int main(void){ Current220 *current220 = new Current220; Adapter *adapter = new Adapter(current220); adapter->useCurrent18(); delete current220; return 0; }
(2)、运行结果
本文出自 “wait0804” 博客,请务必保留此出处http://wait0804.blog.51cto.com/11586096/1885895
以上是关于装饰模式和适配器模式的主要内容,如果未能解决你的问题,请参考以下文章