1.UML类图
Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义一个具体对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。
2.示例代码
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();
addBehavior();
}
private void addBehavior() {
System.out.println("具体装饰对象B的功能");
}
}
public class Client {
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();
}
}
3.特点
装饰模式动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更灵活。装饰者模式把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了。它把类中的装饰功能从类中搬移去除,这样可以简化原有的类,有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。