设计模式 – 装饰器模式(Decorator Pattern)

内容纲要

装饰器模式(Decorator Pattern)是一种结构型设计模式,它允许你在不修改原始对象代码的情况下,动态地为对象添加新的功能。装饰器类与原始类实现相同的接口,并通过组合的方式在运行时添加新功能。

以下是一个简单的Java实现:

  1. 创建一个组件接口(Component Interface),表示原始对象和装饰器对象共同实现的接口:
public interface Component {
    void operation();
}
  1. 创建一个具体组件(Concrete Component),实现组件接口:
public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("Concrete Component operation.");
    }
}
  1. 创建一个抽象装饰器类(Decorator),实现组件接口,并持有一个组件对象的引用:
public abstract class Decorator implements Component {
    protected Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        component.operation();
    }
}
  1. 创建具体装饰器类(Concrete Decorator),继承抽象装饰器类,并为组件添加新功能:
public class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        addedFunctionA();
    }

    private void addedFunctionA() {
        System.out.println("Added function A from Concrete Decorator A.");
    }
}

public class ConcreteDecoratorB extends Decorator {
    public ConcreteDecoratorB(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        addedFunctionB();
    }

    private void addedFunctionB() {
        System.out.println("Added function B from Concrete Decorator B.");
    }
}
  1. 使用装饰器模式创建对象:
public class Main {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        Component decoratorA = new ConcreteDecoratorA(component);
        Component decoratorB = new ConcreteDecoratorB(decoratorA);

        decoratorB.operation();
    }
}

运行上述代码,你将看到:

Concrete Component operation.
Added function A from Concrete Decorator A.
Added function B from Concrete Decorator B.

装饰器模式让你可以在不修改原始对象代码的情况下,为对象添加新功能。这种模式在需要扩展对象功能时非常有用,因为你可以通过组合多个装饰器对象来实现任意组合的功能。

Leave a Comment

您的电子邮箱地址不会被公开。 必填项已用*标注

close
arrow_upward