• 从设计模式看Java IO


    一、装饰者模式

    一个类的功能扩展可以有两种方式 :

    (1) 类的继承 ( 高耦合,会产生更多的子类,从而引起类的爆炸 )
    (2) 对象组合即装饰模式 ( 降耦,不会创造更多的子类 ) 动态的为对象添加功能) 所以类应该对扩展开放,对修改关闭 。
     
    装饰者设计模式注意事项: 
    (1) 装饰者和被装饰者必须具有相同的超类型。
    (2) 装饰者即可以包装被装饰者,也可以包装装饰者。往往利用多层包装来达到目的。

    (3) 装饰者中组合了被装饰者对象 ( 装饰类的关键特征 ) 。使得我们能够通过嵌套装饰来动态扩展行为。

     

    四个概念:

    (1) 抽象的构件角色( Component):
    它是一个接口,封装了将要添加的功能(方法)。
    它相当于 IO 中的 InputStream 。( 或 OutputStream )

    (2) 具体的构件角色( ConcreteComponent ):
    它是一个类,该类实现了 Component 接口,因此该类中封装了将要添加的功能的一种实现方法。

    (3) 装饰角色( Decorator): 它是一个类,该类也实现了 Component 接口,同时也必须持有接口 Component 的对象的引用,
    该类也实现了 Component 接口中的方法。
    a: 该类的构造方法需要传递过来一个 Component 对象的引用。
    b: 重写的方法(即是添加的功能)需要调用 Component 对象的该方法。

    (4) 具体的装饰角色( Decorator 类的子类,可以有一个,也可以有多个):
    这些类继承了类 Decorator, 要重写父类的方法(要添加的功能),和自身的构造方法。
    a: 构造方法要用到 super。
    b: 第一步: super 父类的该方法。
         第二步:添加自己的功能(一些句子)。

     

     

    装饰者 :Java IO 框架和 Collection 框架

    ( 一 ) Java IO 框架 J DK5.0 中 60 多个 IO 流类组成了四大家族: InputStream , OutputStream , Reader , Writer 。

    InputStream / OutputStream 是对字节序列进行操作的抽象类。

    Reader/Writer 是基于 Unicode 代码单元进行操作的抽象类。

     

    InputStream 具有读入功能的抽象被装饰器。

    FileInputStream   具有读入文件功能的具体被装饰器

      FilterInputStream   具备装饰器的抽象意义

      BufferedInputStream    具有具体功能 ( 缓冲功能 ) 的装饰器

     

     

     InputStream :字节序列输入类鼻祖 ---------------------- Component
    • public abstract class InputStream implements Closeable
    • 最基本的读取字节的抽象方法,供子类扩展。
    • public abstract int read() throws IOException ;
     FileInputStream : 读取文件中的字节流类 继承 InputStream ------------ ConcreteComponent
    • public class FileInputStream extends InputStream
    • 构造函数
    • public FileInputStream (String name) throws FileNotFoundException
    • 本地方法,与操作系统低层交互的具体读入方法
    • public native int read() throws IOException ; ( 基于本地方法的底层实现 ,java 调用非 java 程序实现 )

     

    • FilterInputStream : 过滤流类,起装饰器作用,用于对输入装配各种功能 ------------ Decorator
    • public class FilterInputStream extends InputStream
    • 用于记录被装饰者,也就是需要装配新功能的 InputStream 对象
    • protected volatile InputStream in;
    • 构造装饰器  in 用来设置需要被包装 InputStream 对象
    • protected FilterInputStream ( InputStream in) { this.in = in; // 设置需要被包装 InputStream 对象 }
    • 读入字节
    • public int read() throws IOException { return in.read (); }
    • BufferedInputStream : 使输入流具有缓冲功能,是一种可以装配缓冲功能的装饰器,继承 FilterInputStream ------------------ConcreteDecorator
    • public class BufferedInputStream extends FilterInputStream
    • // 构造器      in 就是被装配缓冲功能的 InputStream

    public BufferedInputStream ( InputStream in) { this(in, defaultBufferSize );

    public readLine(){}

  • 相关阅读:
    P站画师 GTZ taejune 精选4k插画壁纸
    点、向量与坐标系
    一些几何
    画直线算法 Line drawing algorithm
    DX11 学习大纲
    插值 Interpolation
    The History of Computer Graphics
    vue中的请求拦截响应
    Event loop
    小程序使用wx.navigateTo()跳转失败
  • 原文地址:https://www.cnblogs.com/maydow/p/4593630.html
Copyright © 2020-2023  润新知