一、装饰模式
动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
将不同的装饰功能,即需要向原有类添加的功能集成于不同的类当中,让这个类包装所要修饰的对象。
那么当需要有顺序地执行特殊的行为时,就可以采用装饰模式了。
二、实现思路
abstract class Component{
public abstract void operation();
}
//原有类
class ConcreteComponent extends Component{
@Override
public void operation() {
System.out.println("具体对象的操作");
}
}
//装饰类
class Decorator extends Component{
protected Component component;
//将需要装饰的类设置进Decorator
public void setComponent(Component component){
this.component=component;
}
//执行原有操作
@Override
public void operation() {
if (component!=null){
component.operation();
}
}
}
class ConcreteDecoratorA extends Decorator{
private String addedState;
@Override
public void operation() {
super.operation();
addedState="new state";
System.out.println("具体装饰对象A的操作");
}
}
/**
* 首先运行原Component的operation(),
* 再执行本类的功能,如addedBehavior(),
* 相当于对原Component进行了装饰
*/
class ConcreteDecoratorB extends Decorator{
@Override
public void operation() {
super.operation();
addedBehavior();
System.out.println("具体装饰对象B的操作结束");
}
private void addedBehavior(){
System.out.println("装饰对象B添加行为");
}
}
//客户端代码
class DecorationMain{
public static void main(String[] args) {
ConcreteComponent c=new ConcreteComponent();
ConcreteDecoratorA d1=new ConcreteDecoratorA();
ConcreteDecoratorB d2=new ConcreteDecoratorB();
/**
* 其实就是:
* 首先用ConcreteComponent实例化对象c,
* 然后用ConcreteDecoratorA的实例化对象d1来包装c,
* 再用ConcreteDecoratorB的对象d2来包装d1,
* 最后执行d2的operation()方法
*/
d1.setComponent(c);
d2.setComponent(d1);
d2.operation();
}
}

来源:https://www.cnblogs.com/chen-ying/p/11072969.html