大话设计模式----装饰模式

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

 代码示例:

public abstract class Component {

public abstract void operation();

}

public class ConcreteComponent extends Component {

@Override
public void operation() {
System.out.println("具体对象的操作");
}
}

public class Decorator extends Component {

protected Component component;

public void setComponent(Component component) {
this.component = component;
}

@Override
public void operation() {
if(component != null){
component.operation();
}
}
}

public class ConcreteDecoratorA extends Decorator {

private String addedState;

@Override
public void operation(){
super.operation();
addedState = "New State";
System.out.println("具体装饰对象A的操作");
}
}

public class ConcreteDecoratorB extends Decorator {

@Override
public void operation(){
super.operation();
addedBehavior();
System.out.println("具体装饰对象B的操作");
}

public void addedBehavior(){
System.out.println("装饰对象B的额外操作");
}

}

public class TestDecorator {

public static void main(String[] args) {
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA a = new ConcreteDecoratorA();
ConcreteDecoratorB b = new ConcreteDecoratorB();

c.operation();
System.out.println("--------------------------");
a.setComponent(c);
a.operation();
System.out.println("--------------------------");
b.setComponent(a);
b.operation();
System.out.println("--------------------------");
}
}

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

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

装饰模式是利用SetComponent来对对象进行包装的。每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。

总结:

  装饰模式是为已有功能动态地添加更多功能的一种方式。当系统需要添加新功能的时候,是向旧的类中添加新的代码,这些新的代码通常装饰了原有类的核心职责或主要行为,加入新的逻辑,从而增加了主类的复杂度。装饰模式提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了。

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

扫描二维码关注公众号,回复: 7426012 查看本文章

猜你喜欢

转载自www.cnblogs.com/zsmcwp/p/11622754.html
今日推荐