首页 > 代码库 > 装饰模式和适配器模式
装饰模式和适配器模式
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
装饰模式和适配器模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。