结构型模式之装饰模式

装饰模式(Decorator Pattern)是一种比较常见的模式。

定义:

  • 动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

装饰模式类图如下所示。

装饰模式有以下4个角色。

  • 抽象构件(Component)角色:用于规范需要装饰的对象(原始对象)。
  • 具体构件(ConcreteComponent)角色:实现抽象构件接口,定义一个需要装饰的原始类。
  • 装饰(Decorator)角色:持有一个构件对象的实例,并定义一个与抽象构件接口一致的接口,
  • 具体装饰角色:负责对构件对象进行装饰。

Component.java

public interface Component {
    public void operation();
}

ConcreteComponent.java

public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("业务代码");
    }
}

Decorator.java

public abstract class Decorator implements Component {
    private Component component = null;
    public Decorator(Component component) {
        this.component = component;
    }
    @Override
    public void operation() {
        this.component.operation();
    }
}

ConcreteDecorator.java

public class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }
    // 定义自己的方法
    public void selfMethod() {
        System.out.println("修饰");
    }
    // 重写operation
    @Override
    public void operation() {
        this.selfMethod();
        super.operation();
    }
}

Client.java

public class Client {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        // 进行装饰
        component = new ConcreteDecorator(component);
        component.operation();
    }
}

优点:

  • 装饰类和被装饰类可以独立发展,而不会相互耦合。即Component类无须知道Decorator类,Decorator类是从外部来扩展Component类的功能,而Decorator也不用知道具体的构件。
  • 装饰模式是继承关系的一个替代方案。装饰类Decorator,不管装饰多少层,返回的对象还是Component.
  • 装饰模式可以动态地扩展一个实现类的功能。

缺点:

  • 多层的装饰是比较复杂的。

应用场景:

  • 需要扩展一个类的功能,或给一个类增加附加功能。
  • 需要动态地给一个对象增加功能,这些功能可以再动态地撤销。
  • 需要为一批类进行改装或加装功能。

装饰模式是对继承的有力补充。单纯使用继承时,在一些情况下就会增加很多子类,而且灵活性较差,维护也不容易。装饰模式可以替代继承,解决类膨胀的问题,如Java基础类库中的输入输出流相关的类大量使用了装饰模式。

摘自:

青岛东合信息技术有限公司 . 设计模式(Java版) .  电子工业出版社,2012,78-80.

原文地址:https://www.cnblogs.com/yewen1234/p/10093789.html