设计模式(五)--装饰模式

来源:互联网 发布:应用排名优化机制 编辑:程序博客网 时间:2024/06/06 16:31

定义

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


结构图

这里写图片描述


例子

// 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. 装饰模式有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。
1 0
原创粉丝点击