Decorator Pattern (装饰者模式)

时间:2023-03-09 20:21:13
Decorator Pattern (装饰者模式)

装饰者模式( Decorator Pattern )

意图 : 动态的给一个对象添加一些额外的功能,IO这块内容体现出了装饰模式,Decorator模式相比生成子类更为灵活。

角色 :

1)抽象构件角色(Component)--- 定义成一个接口类型

2)具体构件角色 (ConcreteComponent) --- 该类(被装饰者)实现了 Component 接口,

3)装饰角色 (Decorator) --- 该类实现了 Component 接口,并持有 Component接口的引用

4)具体装饰角色 (ConcreteDecorator) --- 该类继承了装饰类

UML实现:

Decorator Pattern (装饰者模式)

代码实现:

Component.java

  1. package com.decorator ;
  2. //抽象构件角色
  3. public interface Component
  4. {
  5. public void operation() ;
  6. }

ConcreteComponent.java

  1. package com.decorator ;
  2. //具体构件角色
  3. public class ConcreteComponent implements Component
  4. {
  5. public void operation()
  6. {
  7. System.out.println("实现功能A") ;
  8. }
  9. }

Decorator.java

  1. package com.decorator ;
  2. //装饰角色,持有一个构件角色的引用
  3. public class Decorator implements Component
  4. {
  5. Component component = null ;
  6. public Decorator(Component component)
  7. {
  8. this.component = component ;
  9. }
  10. public void operation()
  11. {
  12. this.component.operation() ;
  13. }
  14. }

ConcreteDecoratorA.java

  1. package com.decorator ;
  2. //具体装饰角色A
  3. public class ConcreteDecoratorA extends Decorator
  4. {
  5. public ConcreteDecoratorA(Component component)
  6. {
  7. super(component) ;
  8. }
  9. public void operation()
  10. {
  11. super.operation() ;
  12. System.out.println("实现功能B") ;
  13. }
  14. }

ConcreteDecoratorB.java

  1. package com.decorator ;
  2. //具体装饰角色B
  3. public class ConcreteDecoratorB extends Decorator
  4. {
  5. public ConcreteDecoratorB(Component component)
  6. {
  7. super(component) ;
  8. }
  9. public void operation()
  10. {
  11. super.operation() ;
  12. System.out.println("实现功能C") ;
  13. }
  14. }

Client.java

  1. package com.decorator ;
  2. public class Client
  3. {
  4. public static void main(String[] args)
  5. {
  6. //装饰者一般不用出现在客户端 , 因它内部自己会处理
  7. //ConcreteComponent cc = new ConcreteComponent() ;
  8. //ConcreteDecoratorA cd = new ConcreteDecoratorA(cc) ;
  9. //ConcreteDecoratorB cd2 = new ConcreteDecoratorB(cd) ;
  10. //cd2.operation() ;
  11. //上面的代码等价于下面的代码
  12. ConcreteDecoratorB cd = new ConcreteDecoratorB(new ConcreteDecoratorA(new ConcreteComponent())) ;
  13. cd.operation() ;
  14. }
  15. }

小结:

装饰者和被装饰者拥有共同的接口;

装饰者一般不用客户端去调用 , 因它内部自己会处理;

可以用一个或多个装饰者去包装一个对象,具体装饰类和装饰类可以组合成多种行为;