装饰模式(Decorator):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰者比生成子类更灵活。
package com.decorator;
public abstract class Component {
public abstract void operation();
}
package com.decorator;
public class ConcreteComponent extends Component{
@Override
public void operation() {
System.out.println("具体操作的对象。");
}
}
package com.decorator;
public abstract class Decorator extends Component{
protected Component component;
public void setComponent(Component component) {
this.component = component;
}
public void operation() {
if(component != null) {
component.operation();
}
}
}
package com.decorator;
public class ConcreteDecoratorA extends Decorator{
private String addedState;
public void operation() {
super.operation();
addedState = "New State";
System.out.println("具体装饰对象A的操作");
}
}
package com.decorator;
public class ConcreteDecoratorB extends Decorator{
public void operation() {
super.operation();
addedBehavior();
System.out.println("具体装饰对象B的操作");
}
private void addedBehavior() {
System.out.println("B类独有的方法");
}
}
package com.decorator;
public class Test {
public static void main(String[] args) {
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA a = new ConcreteDecoratorA();
ConcreteDecoratorB b = new ConcreteDecoratorB();
a.setComponent(c);
b.setComponent(a);
b.operation();
}
}
Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcretrComponent是定义了一个具体的对象,也可以给这个对象添加一下职责。Decorator,修饰抽象类,继承了Component,从外类扩展Component类的功能。但对于Component来说,是无需知道Decorator的存在的,至于ConcretrComponent就是具体的装饰对象,起到给Component添加职责的功能。
装饰者模式为了已有功能动态地添加更多功能的一种方式,当系统需要新功能的时候,是向旧的类中添加新的代码,这些新加的代码通常装饰了原有类的核心职责或主要行为,在主类中加入了新的字段,新的方法,新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要,而装饰模式却提供了一个非常好的解决方案,它把每个类要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当要执行特殊行为时,客户代码就可以在运行时根据需要有选择地,按顺序地使用装饰功能包装对象了。
装饰模式的优点就是把类中的装饰功能从类中搬移去除,这样可以简化原有的类,有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中的重复的装饰逻辑。