【嵌入式c++】设计模式之装饰者模式(Decorator )

Decorator

动机(Motivation)

  • 在某些情况下我们可能会“过度地使用继承来扩展对象的功能”,由于继承为类型引入的静态特质,使得这种扩展方式缺乏灵活性;
    并且随着子类的增多(扩展功能的增多),各种子类的组合(扩展功能的组合)会导致更多子类的膨胀。
  • 如何使“对象功能的扩展”能够根据需要来动态地实现?同时避免“扩展功能的增多”带来的子类膨胀问题?从而使得任何“功能扩展变化”所导致的影响将为最低?

模式定义

动态(组合)地给一个对象增加一些额外的职责。就增加功能而言,Decorator模式比生成子类(继承)更为灵活(消除重复代码 & 减少子类个数)。
——《设计模式》GoF

要点总结

  • 通过采用组合而非继承的手法, Decorator模式实现了在运行时动态扩展对象功能的能力,而且可以根据需要扩展多个功能。
    避免了使用继承带来的“灵活性差”和“多子类衍生问题”。
  • Decorator类在接口上表现为is-a Component的继承关系,即Decorator类继承了Component类所具有的接口。
    但在实现上又表现为has-a Component的组合关系,即Decorator类又使用了另外一个Component类。
  • Decorator模式的目的并非解决“多子类衍生的多继承”问题,Decorator模式应用的要点在于解决“主体类在多个方向上的扩展功能”——是为“装饰”的含义。

代码结构

.

├── build.sh
├── clearBuild.sh
├── CMakeLists.txt
├── src 
│   ├── examStu.cpp
│   ├── include
│   │   └── examStu.h
│   └── main.cpp

源码例子

examStu.h

#ifndef _EXANSTU__
#define _EXANSTU__

#include <iostream>
#include <string>
#include <vector>
#include <list>

using namespace std;


class Phone
{
    
    
public:

    virtual ~Phone() = default;
    virtual void ShowDecorate() = 0;

private:

};



class Iphone :public  Phone
{
    
    
public:

    ~Iphone(){
    
    };
    void ShowDecorate() override 
    {
    
    
        cout << "original Iphone" << endl;
    }

private:

};



class DecoratorProtector :public  Phone
{
    
    
public:

    DecoratorProtector(Phone* p )
    {
    
    
        this->pPhone = p;
    }
    ~DecoratorProtector(){
    
    };

    void ShowDecorate() override 
    {
    
    
        pPhone->ShowDecorate();
        cout << "add  Iphone :  Protector" << endl;
    }

private:
    Phone * pPhone;
};



class DecoratorShell :public  Phone
{
    
    
public:

    DecoratorShell(Phone* p )
    {
    
    
        this->pPhone = p;
    }
    ~DecoratorShell(){
    
    };

    void ShowDecorate() override 
    {
    
    
        pPhone->ShowDecorate();
        cout << "add  Iphone :  Shell" << endl;
    }

private:
    Phone * pPhone;
};

#endif

main.cpp

#include <iostream>
#include <string>
#include <memory>

#include "examStu.h"

using namespace std;


int main()
{
    
    
    Phone * pIphone = new Iphone();
    Phone * pDecorator  = new  DecoratorProtector(pIphone);
    Phone * pShell  = new  DecoratorShell(pDecorator);
    
    pDecorator->ShowDecorate();
    pShell->ShowDecorate();

    delete pIphone;
    delete pDecorator;
    delete pShell;
    
    pIphone = nullptr;
    pDecorator = nullptr;
    pShell = nullptr;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_15555275/article/details/109469174