1.定义
装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
2.结构图
3.代码
Component
public interface Component {
public void operation();
}
Decorator
public abstract class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
ConcreteComponent
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("墙");
}
}
ConcreteDecoratorA
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
System.out.println("刷白墙");
super.operation();
}
}
ConcreteDecoratorB
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
System.out.println("贴墙纸");
super.operation();
}
}
Test
public class Test {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Decorator decorator = new ConcreteDecoratorB(new ConcreteDecoratorA(component));
decorator.operation();
}
}
4.实际应用中的例子:java io