定义与介绍
优点:
- 装饰者是继承的有力补充,比继承灵活,在不改变原有对象的情况下,动态的给一个对象扩展功能,即插即用
- 通过使用不用装饰类及这些装饰类的排列组合,可以实现不同效果
缺点:
- 装饰者模式造成很多的策略类,增加维护难度。
策略模式的实现
/**
* 抽象构件
*/
public interface Component {
void option();
}
/**
* 具体构件
*/
public class ConcreteComponent implements Component {
@Override
public void option() {
System.out.println("具体构件方法执行!");
}
}
/**
* 抽象装饰
*/
public class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void option() {
System.out.println("抽象前置装饰操作");
component.option();
System.out.println("抽象后置装饰操作");
}
}
/**
* 具体装饰
*/
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
@Override
public void option(){
// 调用抽象装饰option方法
super.option();
System.out.println("具体装饰增强逻辑");
}
}
/**
* 测试类
*/
public class TestDemo01 {
public static void main(String[] args) {
// 在创建具体装饰时传入具体构件对象
ConcreteDecorator concreteDecorator = new ConcreteDecorator(new ConcreteComponent());
concreteDecorator.option();
}
}
// 执行结果
抽象装饰操作
具体构件方法执行!
抽象装饰操作
具体装饰增强逻辑