文章摘要: 装饰器模式使用总结。
简介
简要说明
- 装饰器模式(Decorator Pattern)是一种结构型设计模式。
- 允许向一个现有的对象添加新的功能,同时又不改变其结构。
- 这种模式属于对象结构型模式,它是作为现有类的一个包装。
主要功能
- 在不改变接口的前提下,增强类的性能。
- 通过使用不同的具体装饰类以及这些装饰类的排列组合,可以实现不同的效果。
- 可以对一个对象进行多次装饰,创造出不同行为的组合。
注意事项
- 装饰器模式会产生很多小对象,这些小对象增加了系统的复杂度。
- 装饰器模式比继承更加灵活,但是过度使用会导致系统中类的数目迅速增加。
- 应该在确有必要时使用装饰器模式,避免无谓的装饰。
适用场景
- 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
- 当不能采用生成子类的方法进行扩充时,如类定义被隐藏或者类定义是终极类。
Java 8
案例
// 定义一个Component接口,这是装饰者和被装饰者的共同接口
interface Component {
// 定义一个操作方法,所有实现类都需要实现这个方法
void operation();
}
// ConcreteComponent是Component接口的具体实现,它是被装饰的对象
class ConcreteComponent implements Component {
// 实现operation方法
@Override
public void operation() {
System.out.println("ConcreteComponent operation");
}
}
// Decorator是一个抽象类,实现了Component接口,用于扩展Component的功能
abstract class Decorator implements Component {
// 持有一个Component类型的引用,可以是ConcreteComponent或者另一个Decorator
protected Component component;
// 构造方法,接收一个Component对象
public Decorator(Component component) {
this.component = component;
}
// 实现operation方法,调用被装饰对象的operation方法
@Override
public void operation() {
component.operation();
}
}
// ConcreteDecoratorA是Decorator的具体实现,它添加了额外的行为
class ConcreteDecoratorA extends Decorator {
// 构造方法,调用父类的构造方法
public ConcreteDecoratorA(Component component) {
super(component);
}
// 重写operation方法,在调用被装饰对象的方法之后添加额外的行为
@Override
public void operation() {
super.operation(); // 调用被装饰对象的operation方法
addedBehavior(); // 添加额外的行为
}
// 添加额外的行为
private void addedBehavior() {
System.out.println("ConcreteDecoratorA added behavior");
}
}
// ConcreteDecoratorB是另一个Decorator的具体实现,它也添加了额外的行为
class ConcreteDecoratorB extends Decorator {
// 构造方法,调用父类的构造方法
public ConcreteDecoratorB(Component component) {
super(component);
}
// 重写operation方法,在调用被装饰对象的方法之后添加额外的行为
@Override
public void operation() {
super.operation(); // 调用被装饰对象的operation方法
addedBehavior(); // 添加额外的行为
}
// 添加额外的行为
private void addedBehavior() {
System.out.println("ConcreteDecoratorB added behavior");
}
}
// 客户端代码,使用装饰器模式
public class DecoratorPatternDemo {
public static void main(String[] args) {
// 创建一个ConcreteComponent对象
Component component = new ConcreteComponent();
// 使用ConcreteDecoratorA装饰ConcreteComponent
Component decoratorA = new ConcreteDecoratorA(component);
// 使用ConcreteDecoratorB装饰ConcreteDecoratorA
Component decoratorB = new ConcreteDecoratorB(decoratorA);
// 执行operation方法,将会依次调用ConcreteComponent、ConcreteDecoratorA和ConcreteDecoratorB的operation方法
decoratorB.operation();
}
}
注释
- 在这个例子中,我们定义了一个组件接口
Component和一个具体的组件实现ConcreteComponent。然后我们定义了一个装饰器抽象类Decorator,它实现了Component接口并持有一个Component对象的引用。ConcreteDecoratorA和ConcreteDecoratorB是两个具体的装饰器类,它们扩展了Decorator类并添加了额外的行为。 - 在客户端代码中,我们首先创建了一个
ConcreteComponent对象,然后使用ConcreteDecoratorA和ConcreteDecoratorB对其进行装饰。当我们调用decoratorB.operation()时,它将依次执行ConcreteComponent、ConcreteDecoratorA和ConcreteDecoratorB的operation方法,从而实现了功能的动态添加。