《大話設計模式》讀書筆記(C++代碼實現) 第六章:裝飾模式

來源:互聯網
上載者:User

裝飾模式(Decorator)

  動態給一個對象添加一些額外的職責,就增加功能來說,裝飾模式比產生子類更靈活。

// FineryTest01.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include <string>using namespace std;class Person{private :    char* name;public :    Person(){    name = 0; }    ~Person()    {        if(name != 0)        {            delete []name;        }    }    Person(char* name)    {        //this->name = name;        char* p = name;        int len = 0;        while(*p != 0)        {            p++;    len++;        }        this->name = new char[len + 1];        memcpy(this->name, name, len+1);    }    virtual void Show()    {        cout<<"裝扮的"<<this->name<<endl;    }};//服飾類class Finery : public Person{protected :    Person *person;public :    void Decorate(Person *p)    {        this->person = p;    }    virtual void Show()    {        if(person != NULL)        {            person->Show();        }    }};//具體服飾類class TShirts : public Finery{public :        virtual void Show()    {        cout<<" [大T恤] ";        Finery::Show();    }};class BigTrouser : public Finery{public :    virtual void Show()    {        cout<<" [垮褲] ";        Finery::Show();    }};class Sneaker : public Finery{public :    virtual void Show()    {        cout<<" [運動鞋] ";        Finery::Show();    }};int _tmain(int argc, _TCHAR* argv[]){    char* name = "小菜";    Person per(name);    cout<<"第一種裝扮:"<<endl;    BigTrouser bt;    TShirts ts;    Sneaker sn;    bt.Decorate(&per);    ts.Decorate(&bt);    sn.Decorate(&ts);    sn.Show();    system("pause");    return 0;}

程式啟動並執行結果:

第一種裝扮: [運動鞋]  [大T恤]  [垮褲] 裝扮的小菜

這個程式中需要注意的是,使用C#編程時,在具體服飾類裡調用base.Show(),即調用基類同名方法,實際上調用的是被重寫的方法。而使用C++,需要將所有Show函數全部加上virtual關鍵字,它才能找到上一次執行個體化對象時所填充的函數。具體細節去看C++虛函數表。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.