结构型模式-装饰者

定义:装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
意图:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类(继承)更为灵活。
主要解决:一般的我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。
使用:在不想增加很多子类的情况下扩展类,将具体功能职责划分,同时继承装饰者模式。
关键代码:

  1. Component 类充当抽象角色,不应该具体实现。
  2. 修饰类引用和继承 Component 类,具体扩展类重写父类方法。**

缺点:多层装饰比较复杂。
使用场景: 1. 扩展一个类的功能。 2. 动态增加功能,动态撤销。**

  1. /**
  2. * 装饰者抽象接口
  3. */
  4. public interface Component {
  5. String methodA();
  6. int methodB();
  7. }
  1. /**
  2. * 装饰者,包含一个被装饰者,基于被装饰者实现的前后增强实现逻辑,对方法结果进行修改,扩展功能。
  3. * 有点类似于委托的机制或者说职责链,承上启下作用
  4. * 例如:
  5. * 1. 本示例,多重促销活动的叠加,不打折 + 满3件9.9折 + 满10件9.8 + 满200百减10元
  6. * 2. JDK,IO流处理:FileInputStream + BufferedInputStream + LineNumberInputSteam
  7. */
  8. public class Decorator implements Component {
  9. protected Component component;
  10. public Decorator(Component component) {
  11. this.component = component;
  12. }
  13. public String methodA() {
  14. return this.component.methodA();
  15. }
  16. public int methodB() {
  17. return this.component.methodB();
  18. }
  19. }
  1. /**
  2. * 被装饰者(相当于内衣-初始)
  3. */
  4. public class ConcreteComponent implements Component {
  5. public String methodA() {
  6. return "concrete-object";
  7. }
  8. public int methodB() {
  9. return 100;
  10. }
  11. }
  1. /**
  2. * 被装饰者A
  3. */
  4. public class DecoratorA extends Decorator {
  5. public DecoratorA(Component component) {
  6. super(component);
  7. }
  8. public String methodA() {
  9. return this.component.methodA() + " + A";
  10. }
  11. public int methodB() {
  12. return this.component.methodB() + 10;
  13. }
  14. }
  15. /**
  16. * 被装饰者B
  17. */
  18. public class DecoratorB extends Decorator {
  19. public DecoratorB(Component component) {
  20. super(component);
  21. }
  22. public String methodA() {
  23. return this.component.methodA() + " + B";
  24. }
  25. public int methodB() {
  26. return this.component.methodB() + 9;
  27. }
  28. }
  29. public class DecoratorSample {
  30. public static void main(String[] args) {
  31. // 装饰者成为被装饰者,通过这种方式可以装饰无数个被装饰者
  32. Component a = new DecoratorA(new ConcreteComponent());
  33. System.out.println(a.methodA());
  34. System.out.println(a.methodB());
  35. Component b = new DecoratorB(a);
  36. System.out.println(b.methodA());
  37. System.out.println(b.methodB());
  38. }
  39. }
  40. --运行结果
  41. concrete-object + A
  42. 110
  43. concrete-object + A + B
  44. 119

image.png