深圳幻海软件技术有限公司 欢迎您!

如何动态地给一个类增加功能?

2023-02-28

哈喽,大家好,我是指北君。今天给大家介绍另一种常用的设计模式——装饰器模式。1.什么是装饰器模式?Attachadditionalresponsibilitiestoanobjectdynamicallykeepingthesameinterface.Decoratorsprovideaflexib

哈喽,大家好,我是指北君。

今天给大家介绍另一种常用的设计模式——装饰器模式。

1.什么是装饰器模式?

Attach additional responsibilities to an object dynamically keeping the same interface.Decorators provide a flexible alternative to subclassing for extending functionality.

装饰器模式(Decorator Pattern):动态的给一个对象添加额外的职责,就增加功能来说, 装饰模式相比生成子类更为灵活。

说人话:一般的,我们为了扩展一个类经常使用继承方式实现,随着扩展功能的增多,子类会很膨胀。这时候期望在不改变类对象及其类定义的情况下,为对象添加额外功能,这就是装饰器模式。

2.装饰器模式定义

①Component抽象构件

Component是一个接口或者是抽象类, 就是定义我们最核心的对象, 也就是最原始的对象。

②ConcreteComponent 具体构件

ConcreteComponent是最核心、 最原始、 最基本的接口或抽象类的实现, 你要装饰的就是它。

③Decorator装饰角色

一般是一个抽象类, 实现接口或者抽象方法, 它里面可不一定有抽象的方法, 在它的属性里必然有一个private变量指向Component抽象构件。

④ConcreteDecorator 具体装饰角色

ConcreteDecoratorA和ConcreteDecoratorB是两个具体的装饰类, 你要把你最核心的、 最原始的、 最基本的东西装饰成其他东西

3.装饰器模式通用代码实现

/**
 * 抽象构件
 */
public abstract class Component {
    public abstract void operator();
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
/**
 * 具体构件
 */
public class ConcreteComponent extends Component{
    @Override
    public void operator() {
        System.out.println("doSomething");
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
/**
 * 抽象装饰者
 */
public abstract class Decorator extends Component{
    private Component component;

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

    // 委托给被修饰者执行
    @Override
    public void operator() {
        this.component.operator();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
public class ConcreteDecorator1 extends Decorator{
    // 定义被修饰者
    public ConcreteDecorator1(Component component){
        super(component);
    }

    // 定义自己的修饰方法
    public void method1(){
        System.out.println("修饰方法 method1");
    }
    @Override
    public void operator() {
        this.method1();
        super.operator();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

客户端测试:

public class DecoratorClient {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        // 第一次修饰
        component = new ConcreteDecorator1(component);
        // 第二次修饰
        component = new ConcreteDecorator2(component);
        // 修饰后运行
        component.operator();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

打印结果:

4.装饰器模式优点

①装饰模式可以动态地扩展一个实现类的功能。

②装饰类和被装饰类可以独立发展, 而不会相互耦合。换句话说, Component类无须知道Decorator类, Decorator类是从外部来扩展Component类的功能, 而Decorator也不用知道具体的构件。

③装饰模式是继承关系的一个替代方案。我们看装饰类Decorator, 不管装饰多少层, 返回的对象还是Component, 实现的还是is-a的关系

5.装饰器模式应用场景

①、需要扩展一个类的功能, 或给一个类增加附加功能。

②、需要动态地给一个对象增加功能, 这些功能可以再动态地撤销。