装饰模式
装饰模式(Decorator Pattern):动态地给一个对象增加一些额外的职责,就增加对象功能来说, 装饰模式比生成子类实现更为灵活。装饰模式是一种对象结构型模式
//抽象构件
public interface DPComponent {
void operation();
}
//具体构件
public class DPConcreteComponent implements DPComponent {
@Override
public void operation() {
System.out.println("我是具体组件逻辑");
}
}
//抽象装饰类
public class DPDecorator implements DPComponent{
private DPComponent dpComponent;
public DPDecorator(DPComponent dpComponent) {
this.dpComponent = dpComponent;
}
@Override
public void operation() {
dpComponent.operation();
}
}
//具体装饰类
public class DPConcreteDecorator extends DPDecorator {
public DPConcreteDecorator(DPComponent dpComponent) {
super(dpComponent);
}
@Override
public void operation() {
super.operation();
addedBehavior();
}
public void addedBehavior(){
System.out.println("这个我新增的行为");
}
}
public class DPClient {
public static void main(String[] args) {
DPConcreteDecorator decorator = new DPConcreteDecorator(new DPConcreteComponent());
decorator.operation();
System.out.println("=====================================================");
DPConcreteDecorator decorator1 = new DPConcreteDecorator(decorator);
decorator1.operation();
System.out.println("=====================================================");
DPConcreteDecorator decorator2 = new DPConcreteDecorator(decorator1);
decorator2.operation();
}
}
优点
- 对于扩展一个对象的功能,装饰模式比继承更加灵活性,不会导致类的个数急剧增加
- 可以通过一种动态的方式来扩展一个对象的功能,通过配置文件可以在运行时选择不同的 具体装饰类,从而实现不同的行为
- 可以对一个对象进行多次装饰,通过使用不同的具体装饰类以及这些装饰类的排列组合, 可以创造出很多不同行为的组合,得到功能更为强大的对象
- 具体构件类与具体装饰类可以独立变化,用户可以根据需要增加新的具体构件类和具体装 饰类,原有类库代码无须改变,符合“开闭原则”
缺点
- 使用装饰模式进行系统设计时将产生很多小对象,这些对象的区别在于它们之间相互连接 的方式有所不同,而不是它们的类或者属性值有所不同,大量小对象的产生势必会占用更多 的系统资源,在一定程序上影响程序的性能
- 装饰模式提供了一种比继承更加灵活机动的解决方案,但同时也意味着比继承更加易于出 错,排错也很困难,对于多次装饰的对象,调试时寻找错误可能需要逐级排查,较为繁琐
使用场景
- 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
- 当不能采用继承的方式对系统进行扩展或者采用继承不利于系统扩展和维护时可以使用装 饰模式。