装饰者模式

#include <iostream>
#include <string>
using namespace std;

class Person
{
public:
    Person(){}
    Person(string name)
    {
        this->name = name;
    }
    virtual void Show()
    {
        cout<<"装扮的"<<name;
    }
private:
    string name;
};

class Finery: public Person
{
public:
    void Decorate(Person* component)
    {
        this->component = component;
    }
    void Show()
    {
        if(component != NULL)
        {
            component->Show();
        }
    }
protected:
    Person* component;
};

class TShirts: public Finery
{
public:
    void Show()
    {
        cout<<"大T恤 ";
        Finery::Show();
    }
};

class BigTrouser: public Finery
{
public:
    void Show()
    {
        cout<<"垮裤 ";
        Finery::Show();
    }
};

int main()
{
    Person t("小菜");
    TShirts *ts = new TShirts();
    BigTrouser *bt = new BigTrouser();
    bt->Decorate(&t);
    ts->Decorate(bt);
    ts->Show();
}

个人感觉:缺点,如果原有类成员比较多的话,这样装饰者继承于原有类,会浪费很多空间。因为装饰者只装饰原有类的一个方法。

posted on 2017-02-14 11:05  zyz913614263  阅读(141)  评论(0编辑  收藏  举报

导航