装饰者模式( Decorator Pattern )
意图 : 动态的给一个对象添加一些额外的功能,IO这块内容体现出了装饰模式,Decorator模式相比生成子类更为灵活。
角色 :
1)抽象构件角色(Component)--- 定义成一个接口类型
2)具体构件角色 (ConcreteComponent) --- 该类(被装饰者)实现了 Component 接口,
3)装饰角色 (Decorator) --- 该类实现了 Component 接口,并持有 Component接口的引用
4)具体装饰角色 (ConcreteDecorator) --- 该类继承了装饰类
UML实现:
代码实现:
Component.java
- package com.decorator ;
- //抽象构件角色
- public interface Component
- {
- public void operation() ;
- }
ConcreteComponent.java
- package com.decorator ;
- //具体构件角色
- public class ConcreteComponent implements Component
- {
- public void operation()
- {
- System.out.println("实现功能A") ;
- }
- }
Decorator.java
- package com.decorator ;
- //装饰角色,持有一个构件角色的引用
- public class Decorator implements Component
- {
- Component component = null ;
- public Decorator(Component component)
- {
- this.component = component ;
- }
- public void operation()
- {
- this.component.operation() ;
- }
- }
ConcreteDecoratorA.java
- package com.decorator ;
- //具体装饰角色A
- public class ConcreteDecoratorA extends Decorator
- {
- public ConcreteDecoratorA(Component component)
- {
- super(component) ;
- }
- public void operation()
- {
- super.operation() ;
- System.out.println("实现功能B") ;
- }
- }
ConcreteDecoratorB.java
- package com.decorator ;
- //具体装饰角色B
- public class ConcreteDecoratorB extends Decorator
- {
- public ConcreteDecoratorB(Component component)
- {
- super(component) ;
- }
- public void operation()
- {
- super.operation() ;
- System.out.println("实现功能C") ;
- }
- }
Client.java
- package com.decorator ;
- public class Client
- {
- public static void main(String[] args)
- {
- //装饰者一般不用出现在客户端 , 因它内部自己会处理
- //ConcreteComponent cc = new ConcreteComponent() ;
- //ConcreteDecoratorA cd = new ConcreteDecoratorA(cc) ;
- //ConcreteDecoratorB cd2 = new ConcreteDecoratorB(cd) ;
- //cd2.operation() ;
- //上面的代码等价于下面的代码
- ConcreteDecoratorB cd = new ConcreteDecoratorB(new ConcreteDecoratorA(new ConcreteComponent())) ;
- cd.operation() ;
- }
- }
小结:
装饰者和被装饰者拥有共同的接口;
装饰者一般不用客户端去调用 , 因它内部自己会处理;
可以用一个或多个装饰者去包装一个对象,具体装饰类和装饰类可以组合成多种行为;