在實際開發時,你有沒有碰到過這種問題;開發一個類,封裝了一個對象的核心操做,而這些操做就是客戶使用該類時都會去調用的操做;而有一些非核心的操做,可能會使用,也可能不會使用;如今該怎麼辦呢?ios
裝飾模式可以實現動態的爲對象添加功能,是從一個對象外部來給對象添加功能。一般給對象添加功能,要麼直接修改對象添加相應的功能,要麼派生對應的子類來擴展,抑或是使用對象組合的方式。顯然,直接修改對應的類這種方式並不可取。在面向對象的設計中,而咱們也應該儘可能使用對象組合,而不是對象繼承來擴展和複用功能。裝飾器模式就是基於對象組合的方式,能夠很靈活的給對象添加所須要的功能。裝飾器模式的本質就是動態組合。動態是手段,組合纔是目的。總之,裝飾模式是經過把複雜的功能簡單化,分散化,而後再運行期間,根據須要來動態組合的這樣一個模式。它使得咱們能夠給某個對象而不是整個類添加一些功能。 設計模式
Component:定義一個對象接口,能夠給這些對象動態地添加職責;函數
ConcreteComponent:定義一個具體的Component,繼承自Component,重寫了Component類的虛函數;spa
Decorator:維持一個指向Component對象的指針,該指針指向須要被裝飾的對象;並定義一個與Component接口一致的接口;設計
ConcreteDecorator:向組件添加職責。指針
代碼實現:code
#include <iostream> using namespace std; class Component { public: virtual void Operation() = 0; }; class ConcreteComponent : public Component { public: ConcreteComponent() { cout <<" ConcreteComponent "<< endl; } void Operation() { cout<<"I am no decoratored ConcreteComponent"<<endl; } }; class Decorator : public Component { public: Decorator(Component *pComponent) : m_pComponentObj(pComponent) { cout << " Decorator "<<endl; } void Operation() { if (m_pComponentObj != NULL) { m_pComponentObj->Operation(); } } protected: Component *m_pComponentObj; }; class ConcreteDecoratorA : public Decorator { public: ConcreteDecoratorA(Component *pDecorator) : Decorator(pDecorator) { cout << " ConcreteDecoratorA "<<endl; } void Operation() { AddedBehavior(); Decorator::Operation(); } void AddedBehavior() { cout<<"This is added behavior A."<<endl; } }; class ConcreteDecoratorB : public Decorator { public: ConcreteDecoratorB(Component *pDecorator) : Decorator(pDecorator) { cout << " ConcreteDecoratorB "<<endl; } void Operation() { AddedBehavior(); Decorator::Operation(); } void AddedBehavior() { cout<<"This is added behavior B."<<endl; } }; int main() { Component *pComponentObj = new ConcreteComponent(); Decorator *pDecoratorAOjb = new ConcreteDecoratorA(pComponentObj); pDecoratorAOjb->Operation(); cout<<"============================================="<<endl; Decorator *pDecoratorBOjb = new ConcreteDecoratorB(pComponentObj); pDecoratorBOjb->Operation(); cout<<"============================================="<<endl; Decorator *pDecoratorBAOjb = new ConcreteDecoratorB(pDecoratorAOjb); pDecoratorBAOjb->Operation(); cout<<"============================================="<<endl; delete pDecoratorBAOjb; pDecoratorBAOjb = NULL; delete pDecoratorBOjb; pDecoratorBOjb = NULL; delete pDecoratorAOjb; pDecoratorAOjb = NULL; delete pComponentObj; pComponentObj = NULL; }
C++設計模式——橋接模式與裝飾模式都是爲了防止過分的繼承,從而形成子類氾濫的狀況。那麼兩者之間的主要區別是什麼呢?橋接模式的定義是將抽象化與實現化分離(用組合的方式而不是繼承的方式),使得二者能夠獨立變化。能夠減小派生類的增加。若是光從這一點來看的話,和裝飾者差很少,但二者仍是有一些比較重要的區別:對象
轉自:C++設計模式——裝飾模式 blog