装饰者模式( 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 ;
-
- 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 ;
-
- 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)
- {
-
-
-
-
-
-
-
- ConcreteDecoratorB cd = new ConcreteDecoratorB(new ConcreteDecoratorA(new ConcreteComponent())) ;
- cd.operation() ;
-
- }
- }
小结:
装饰者和被装饰者拥有共同的接口;
装饰者一般不用客户端去调用 , 因它内部自己会处理;
可以用一个或多个装饰者去包装一个对象,具体装饰类和装饰类可以组合成多种行为;
Decorator Pattern (装饰者模式)
原文:http://www.cnblogs.com/hoobey/p/5294387.html