設計模式之裝飾者模式Decorator Pattern

來源:互聯網
上載者:User

        近來在讀《Head first設計模式》這本書,感覺很不錯只是書中的代碼是用Java寫的。因為我熟悉的是C++,於是自己寫了C++的例子程式。首先說說我的感受吧,學C++的話,先看《C++ Primer》搞明白了C++的各種文法,對封裝、繼承、多態有初步的認識。然後學點設計模式,設計模式是針對具體案例的解決方案,是前人編程的經驗,很值得借鑒!

        說個具體案例吧,在買電腦的時候我們通常會填一個表單。表單中有電腦、滑鼠、鍵盤、耳機、話筒、清潔套裝等等。賣家會根據我們的選擇計算價格。如果要針對這個案例寫個程式該怎麼處理呢?當然我們最直接的想法就是針對每一個選項設定一個布爾型變數,值為真的時候代表你選擇了,值為假的時候代表你沒選。但是這樣有很多缺陷比方說,我以後要添加新的裝置供客戶選擇怎麼辦?客戶選擇了兩個滑鼠怎麼辦。。。。出現這樣的需求變化時我們只能修改以前寫的代碼。這樣的程式不符合“對擴充開放,對修改關閉”的原則。

       裝飾模式是在不必改變原類檔案和使用繼承的情況下,動態擴充一個對象的功能。它是通過建立一個封裝對象,也就是裝飾來包裹真實的對象。

       下面是我用c++寫的代碼:

#include <iostream>#include <string>using namespace std;class Component{public:virtual float cost(){return price;}virtual string GetDescription(){return description;}private:float price;string description;};class Computer : public Component{public:float cost(){return 5000.0;}string GetDescription(){return "Computer";}};class Mouse : public Component{public:Mouse(Component *com){component=com;}float cost(){return 50+component->cost();}string GetDescription(){return "Mouse "+component->GetDescription();}private:Component *component;};class Battery : public Component{public:Battery(Component *com){component=com;}float cost(){return 200.0+component->cost();}string GetDescription(){return "Battery "+component->GetDescription();}private:Component *component;};void main(){int choose;int flg=0;Component *com;cout<<"Please input your choose:"<<endl;cout<<"1: Computer  2: Mouse  3: Batery  4:Quit"<<endl;while (1){cin>>choose;switch (choose){case 1:com=new Computer();break;case 2:com=new Mouse(com); break;case 3:com=new Battery(com); break;case 4: flg=1; break;default: break;}if (1==flg){flg=0;break;}}cout<<com->GetDescription()<<endl;cout<<com->cost()<<endl;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.