C++设计模式——装饰模式

装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活

 

 

Component是定义一个对象的接口,可以给这些对象动态的添加职责。

ConcreteComponent是定义了一个具体的对象某夜可以给这个对象添加一些职责。

Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的

ConcreteDecorator是具体的装饰对象,起到给Component 添加职责的功能

//装饰模式,动态地给一个对象添加一些额外的职责,就增加功能来说 装饰模式比生成子类更为灵活
#include <iostream>
using namespace std;

//ConcreteComponent即Component
class Person
{
protected:
    string name;
public:
    Person() {};
    Person(string name):name(name) {};
    virtual void show() {
        cout << "装扮的" << name << endl;
    }

};


//Decorator类(装饰类),继承了Persson类,并且弱拥有Person类
class Finery : public Person
{
protected:
    Person* component;
public:
    Finery():component(nullptr){}
    void Decorate(Person* component)
    {
        this->component = component;
    }
    virtual void show()
    {
        if (component)
            component->show();
    }
};

//ConcreteDecorator类
class TShirts : public Finery
{
public:
    virtual    ~TShirts() {}
    virtual void show()
    {
        cout << "Tshirt" << endl;
        Finery::show();
    }
};

//ConcreteDecorator类
class Jeans : public Finery
{
public:
    virtual    ~Jeans() {}
    virtual void show()
    {
        cout << "Jeans" << endl;
        Finery::show();
    }
};

int main()
{
    Person* p = new Person("小菜");
    TShirts* oTShirt = new TShirts();
    Jeans* oJeans = new Jeans();
    oTShirt->Decorate(p);
    oJeans->Decorate(oTShirt);
    oJeans->show();


    delete p; p = nullptr;
    delete oTShirt; oTShirt = nullptr;
    delete oJeans; oJeans = nullptr;
    system("pause");
    return 0;
}

装饰模式,动态地给一个对象添加一些额外的职责,就增加功能而言,装饰模式比生成子类更为灵活
装饰对象的实现和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中
当系统需要新功能的时候,且新的功能仅仅是为了满足一些只在特定情况下使用的情形,这个时候使用装饰模式是很好的
装饰模式可以把要添加的功能放在单独的类中,并让这个类包装他所需要的装饰的对象,当需要执行特殊行为时,客户代码就可以在运行时根据需求有选择的、按顺序的使用装饰功能包装对象了。
优点:

把类中的装饰功能从类中搬移去除,简化原有的类。有效将类的核心职责和装饰功能区分开来,且可以去除相关类中重复的装饰逻辑

参考——大话设计模式

参考——https://blog.csdn.net/weixin_43272766/article/details/90238917 

posted @ 2022-02-22 15:49  冰糖葫芦很乖  阅读(390)  评论(0编辑  收藏  举报