天天看點

設計模式(五)--裝飾模式

定義

裝飾模式,動态地給一個對象添加一些額外的職責,就增加功能來說,裝飾模式比生成子類更加靈活。

結構圖

設計模式(五)--裝飾模式

例子

// Component類,元件類:
class Component
{
protect:
    virtual void Operation();
};

//ConCreteComponent具體元件類:
class ConCreteComponent : public Component
{
public:
    void Operation()
    {
    }
};

//Decorator裝飾器類:
class Decorator : public Component
{
protected:
    Component component;
public:
    void SetComponent(Component component)
    {
        this.component = component;
    }
    void Operation()
    {
        component.Operation();
    }
}

//ConcreteDecoratorA具體裝飾類A:
class ConcreteDecoratorA : public Decorator
{
private:
    string addedState;
public:
    void Operation()
    {
        Decorator::Operation();
        addedState = "New State";
    }
}

//ConcreteDecoratorB具體裝飾類B:
class ConcreteDecoratorB : public Decorator
{
public:
    void Operation()
    {
        Decorator::Operation();
        AddedBehavior();
    }
private:
    void AddedBehavior()
    {}
}

//用戶端調用:
void main()
{
    ConCreteComponent c = new ConCreteComponent();
    ConcreteDecoratorA d1 = new ConcreteDecoratorA();
    ConcreteDecoratorB d2 = new ConcreteDecoratorB();

    d1.SetComponent(c);
    d2.SetComponent(d1);
    d2.Operation();
}
           

适用場景

裝飾模式是為已有功能動态地添加更多功能的一種方式。

特點

裝飾模式是利用SetComponent來對對象進行包裝,這樣每個裝飾對象的實作和如何使用這個對象分離開了,每個裝飾對象隻關心自己的功能,不需要關心如何被添加到對象鍊當中。

如果隻有一個ConcreteComponent類而沒有抽象的Component類,那麼Decorator類可以是ConcreteComponent類的一個子類,同理,如果隻有一個ConcreteDecorator類,那麼就沒有必要建立一個單獨的Decorator類,而可以把Decorator和ConcreteDecorator的責任合并成一個類。

優點

  1. 裝飾模式把每個要裝飾的功能放在了單獨的類中,并讓這個類包裝它所要修飾的對象,是以,當需要執行特殊行為時,客戶代碼就可以在運作時根據需要,有選擇地、按順序地使用裝飾功能包裝對象了。
  2. 裝飾模式把類中的裝飾功能從類中搬移去除,這樣可以簡化原有的類。
  3. 裝飾模式有效地把類的核心職責和裝飾功能區分開了,而且可以去除相關類中重複的裝飾邏輯。

繼續閱讀