菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
15
0

装饰者模式

原创
05/13 14:22
阅读数 46195

#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();
}

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

发表评论

0/200
15 点赞
0 评论
收藏
为你推荐 换一批