一天学习一个设计模式之装饰模式

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

      Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能

1 /**
2  * 抽象构件角色
3  */
4 public interface IComponent {
5     void sampleOperation();
6 }

 

 1 /**
 2  * 具体构件角色
 3  */
 4 public class ConcreteComponent implements IComponent {
 5     @Override
 6     public void sampleOperation() {
 7         //写相关的业务代码
 8         System.out.println("具体对象的操作");
 9     }
10 }
 1 /**
 2  * 装饰角色
 3  */
 4 public class Decorator implements IComponent {
 5     private IComponent component;
 6 
 7     public Decorator(IComponent component) {
 8         this.component = component;
 9     }
10 
11     @Override
12     public void sampleOperation() {
13         //委派给构件
14         if (component!=null) {
15             component.sampleOperation();
16         }
17     }
18 }
 1 public class ConcreteDecoratorA extends Decorator  {
 2 
 3     public ConcreteDecoratorA(IComponent component) {
 4         super(component);
 5     }
 6 
 7     @Override
 8     public void sampleOperation() {
 9         super.sampleOperation();
10         System.out.println("具体装饰对象A的操作");
11     }
12 }
 1 public class ConcreteDecoratorB extends Decorator {
 2 
 3     public ConcreteDecoratorB(IComponent component) {
 4         super(component);
 5     }
 6 
 7     @Override
 8     public void sampleOperation() {
 9         super.sampleOperation();
10         System.out.println("具体装饰对象B的操作");
11     }
12 }
1     public static void main(String[] args) {
2         IComponent c=new ConcreteComponent();
3         ConcreteDecoratorA d1=new ConcreteDecoratorA(c);
4         ConcreteDecoratorB d2=new ConcreteDecoratorB(d1);
5         c.sampleOperation();
6         d1.sampleOperation();
7         d2.sampleOperation();
8     }

 在此代码中,装饰模式是利用构造参数(或专门写方法)来对对象进行包装。这样每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。

 

posted on 2017-12-14 15:21  罗伯特☆狗剩  阅读(112)  评论(0编辑  收藏  举报

导航