装饰模式

1】什么是装饰模式?

装饰模式:动态地给一个对象添加一些额外的职责。

【2】装饰模式代码示例:

代码如下:
#include <string>
#include <iostream>
using namespace std;

class Person
{
private:
    string m_strName;
public:
    Person(string strName)
    {
        m_strName = strName;
    }

    Person(){}

    virtual void show()
    {
        cout << "装扮的是:" << m_strName << endl;
    }
};    

class Finery : public Person
{
protected:
    Person *m_component;
public:
    void decorate(Person* component)
    {
        m_component = component;
    }
    virtual void show()
    {
        m_component->show();
    }
};

class TShirts : public Finery
{
public:
    virtual void show()
    {
        m_component->show();
        cout << "T shirts" << endl;
    }
};

class BigTrouser : public Finery
{
public:
    virtual void show()
    {
        m_component->show();
        cout << "Big Trouser" << endl;
    }
};

int main()
{
    Person *p = new Person("小李");
    BigTrouser *bt = new BigTrouser();
    TShirts *ts = new TShirts();
        
    bt->decorate(p);
    ts->decorate(bt);
    ts->show();

    return 0;
}
原文地址:https://www.cnblogs.com/leijiangtao/p/4534657.html