设计模式(6)---装饰器模式

装饰器模式  Decorator (结构型模式)

1.概述

  装饰模式能够实现动态的为对象添加功能,是从一个对象外部来给对象添加功能。例如:为了快速地从InputStream流读取数据,我们使用BufferedInputStream装饰该流,被它装饰过的流便增加了缓冲数据的功能。装饰器模式可以让我们在运行时动态地增强对象的功能,而不影响客户程序的使用。

2.结构图

3.代码

1 /*
2  * 公共接口
3  */
4 public abstract class Component {
5 
6     public abstract void operation();
7 
8 }
 1 /*
 2  * 这是一个被包装的类
 3  */
 4 public class ConcreteComponent extends Component {
 5 
 6     @Override
 7     public void operation() {
 8         System.out.println("盘子上有    ");
 9         
10     }
11     
12 }
 1 /*
 2  * 装饰器接口
 3  */
 4 public abstract class Decorator extends Component {
 5 
 6     protected Component component;
 7     
 8     public Decorator(Component component) {  
 9             this.component = component;  
10     }
11 
12     @Override
13     public void operation() {
14         component.operation(); 
15     }
16 }

以下是3个具体的装饰物

 1 public class Orange extends Decorator {
 2 
 3     public Orange(Component component) {
 4         super(component);
 5         // TODO Auto-generated constructor stub
 6     }
 7     
 8     @Override
 9     public void operation() {
10         super.operation();
11         System.out.println("橘子  ");
12     }
13 
14 }
 1 public class Banana extends Decorator {
 2 
 3     public Banana(Component component) {
 4         super(component);
 5         // TODO Auto-generated constructor stub
 6     }
 7     
 8     @Override
 9     public void operation() {
10         super.operation();
11         System.out.println("香蕉  ");
12     }
13 
14 }
 1 public class Watermelon extends Decorator {
 2 
 3     public Watermelon(Component component) {
 4         super(component);
 5     }
 6     
 7     @Override
 8     public void operation() {
 9         super.operation();
10         System.out.println("西瓜  ");
11     }
12 
13 }
 1 public class Test {
 2 
 3     public static void main(String[] args) {
 4         //盘子上有香蕉  橘子
 5         Component component = new Orange(new Banana(new ConcreteComponent())) ;
 6         component.operation();
 7         
 8         //盘子上有橘子  西瓜
 9         component = new Watermelon(new Orange(new ConcreteComponent())) ;
10         component.operation();
11 
12     }
13 
14 }

4.适用场合

  (1)需要在不影响其他对象的情况下,以动态、透明的方式给对象添加职责。

  (2)如果不适合使用子类来进行扩展的时候,可以考虑使用装饰器模式。

原文地址:https://www.cnblogs.com/mengchunchen/p/5745199.html