装饰者模式是一种结构型设计模式,它允许你动态地将新功能添加到对象中,同时保持代码的灵活性和可扩展性。在这种模式中,一个对象可以被多个装饰器包装,每个装饰器都可以添加一些额外的功能。
下面是装饰者模式的代码实现步骤:
1. 定义一个抽象组件(Component)接口,它是被装饰的对象的基本接口,定义了被装饰对象的基本行为。
2. 实现一个具体组件(ConcreteComponent)类,它是抽象组件的具体实现,也就是被装饰的对象。
3. 定义一个抽象装饰器(Decorator)类,它也实现了抽象组件接口,但是它包含一个指向抽象组件的引用,同时也可以包含其他装饰器。
4. 实现一个具体装饰器(ConcreteDecorator)类,它继承自抽象装饰器类,实现了具体的装饰功能,同时也可以调用父类的方法来保持被装饰对象的基本行为。
5. 在客户端代码中,创建一个具体组件对象,并用一个或多个具体装饰器对象来包装它,从而实现对被装饰对象的功能扩展。
6. 可以动态地添加或删除装饰器,从而实现对被装饰对象的动态修改。
下面是一个简单的装饰者模式的示例代码:
“`
// 抽象组件接口
interface Component {
public void operation();
}
// 具体组件类
class ConcreteComponent implements Component {
public void operation() {
System.out.println("ConcreteComponent operation.");
}
}
// 抽象装饰器类
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
// 具体装饰器类
class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
public void operation() {
super.operation();
System.out.println("ConcreteDecoratorA operation.");
}
}
class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
public void operation() {
super.operation();
System.out.println("ConcreteDecoratorB operation.");
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
component = new ConcreteDecoratorA(component);
component = new ConcreteDecoratorB(component);
component.operation();
}
}
“`
在上面的示例代码中,我们定义了一个抽象组件接口(Component)和一个具体组件类(ConcreteComponent),然后定义了一个抽象装饰器类(Decorator)和两个具体装饰器类(ConcreteDecoratorA和ConcreteDecoratorB)。在客户端代码中,我们创建了一个具体组件对象,并用两个具体装饰器对象来包装它,从而实现了对被装饰对象的功能扩展。最终输出的结果是:
“`
ConcreteComponent operation.
ConcreteDecoratorA operation.
ConcreteDecoratorB operation.
“`