在实际开发时,你有没有碰到过这种问题;开发一个类,封装了一个对象的核心操做,而这些操做就是客户使用该类时都会去调用的操做;而有一些非核心的操做,可能会使用,也可能不会使用;如今该怎么办呢?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