装饰器模式

来源:互联网 发布:化验单制作软件 编辑:程序博客网 时间:2024/05/22 21:18

把所需的功能按正确的顺序串联起来进行控制。

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

abstract class Component{    public abstract void Operation();}
class ConcreteComponent extends Component{    @override    public void Operation()    {        具体对象的操作;    }}

abstract class Decorator extends Component{    protected Component component;    //设置component    public void setComponent(Component component)    {        this.component = component;    }    //重写Operation(),实际执行的是Component的Operation()。    @override    public void Operation()    {        if (component != NULL)            component.Operation();    }}

class ConcreteDecoratorA extends Decorator{    //本类独有的功能,以区别ConcreteDecoratorB    private string addedState;    //首先运行原Component的Operation(),再执行本类的功能,如addedState,相当于对原Component进行了装饰。    @override    public void Operation()    {        super.Operation();        addedState =  “New State”;        具体装饰对象A的操作;    }}
class ConcreteDecoratorB extends Decorator{    //首先运行原Component的Operation(),再执行本类的功能,如AddedBehavior(),相当于对原Component进行了装饰。    @override    public void Operation()    {        super.Operation();        AddedBehavior();        具体装饰对象B的操作;    }    private void AddedBehavior(){ }}
static void main(string[] args){    ConcreteComponent c = new ConcreteComponent();    ConcreteDecoraterA da = new ConcreteDecoraterA();    ConcreteDecoraterB db = new ConcreteDecoraterB();    da.setComponent(c);    db.setComponent(da);    db.Operation();}

装饰模式是利用setComponent来对对象进行包装。

每个装饰对象的实现就和如何使用这个对象分开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。

 

如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。

同理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把DecoratorConcreteDecorator的责任合并成一个类。

 

装饰模式总结:

装饰模式是为已有功能动态的添加更多功能的一种方式。

当系统需要新功能的时候,是向旧的类中添加新的代码

这些新加的代码通常装饰了原有类的核心职责或主要行为

在主类中加入了新的字段、新的方法和新的逻辑,从而增加了主类的复杂度。

而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。

装饰器模式提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择的、按顺序的使用装饰功能包装对象了。

 

装饰模式的优点:

把类中的装饰功能从类中搬移去除,这样可以简化原有的类。

有效的把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。









0 0