您好,登錄后才能下訂單哦!
1、裝飾模式
動態(tài)的給一個對象添加一些額外的職責;
側重于功能的擴展:對其功能可以自由的增加或者減少;
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)、運行結果
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。