java 装饰模式(Decorator or Wrapper)

来源:互联网 发布:2016年云计算市场份额 编辑:程序博客网 时间:2024/06/07 12:52
  • 介绍:装饰模式的作用就是动态的给类添加额外的功能,java IO 的设计就是运用了该设计模式(InputStream有很多装饰子类) 。

  • 通用类图
    这里写图片描述

    • Component:就是原始的待装饰的类
    • ConcreteComponent: 具体的实现类
    • Decorator : 装饰类接口并且包含
    • ConcreteDecoratorA 装饰A类
  • 实例(java.io.InputStream)最好的例子

    • 类图
      这里写图片描述
    • Component : InputStream
    • ConcreteComponent : ByteArrayInputStream,FileInputStream
    • Decorator : FilterInputStream
    • ConcreteDecorator

      • BufferInputStream:用来从硬盘将数据读入到一个内存缓冲区中,并从此缓冲区提供数据。
      • DateInputStream:提供基于多字节的读取方法,可以读取原始数据类型的数据。
      • LineNumberInputStream:提供带有行计算功能的过滤输入流。
      • PushbackInputStream: 提供特殊的功能,可以将已读取的直接“推回”输入流中。
      • 实际使用

        public static void main(String[] args) throws FileNotFoundException {    InputStream a = new FileInputStream("") ;//要装饰FileInputStream    a = new DataInputStream(a);//添加DataInputStream可以读取原始数据类型的数据。    a = new BufferedInputStream(a);//添加缓冲}
  • 使用场景 (参考设计模式之禅)

    • 当一个类我们需要给他动态的添加功能的时候。
    • 动态的给对象增加功能且这些功能可以再动态的撤销
    • 需要为一批兄弟改装或者加装功能
0 0