【IO】- IO 体系中的设计模式-适配器模式

前言

    之前的博客说到了适配器模式的概念和UML类图,这次来聊下IO中的适配器模式。

正文

IO流体系介绍

    InputStreamReader 和OutputStreamWriter 类分别继承了Reader和Writer 接口,但是要创建它们的对象必须在构造函数中传入一个InputStream和OutputStream的实例,InputStreamReader和OutputStreamWriter 的作用 是将InputStream和OutputStream 适配到Reader和Writer。
这里写图片描述

    下面是InputStreamReader的类结构:
这里写图片描述
    这里的适配器角色就是InputStreamReader,被适配的角色是InputStream类代笔的实例对象,目标接口是Reader类。
    可以看到,InputStreamReader实现了Reader接口,并且持有了InputStream的引用,这里是通过StreamDecoder类间接持有的,因为从byte到char 要经过编码。

源码浅析

/******************Reader类(目标类)******************/
package java.io;
public abstract class Reader implements Readable, Closeable {
abstract public int read(char cbuf[], int off, int len) throws IOException;
abstract public void close() throws IOException;
}
/******************InputStreamReader类(适配器类)******************/
public class InputStreamReader extends Reader {
    private final StreamDecoder sd;
    //持有对被适配对象的引用
    public InputStreamReader(InputStream in) {
        super(in);
        try {
            //通过StreamDecoder类间接引用被适配的对象
            sd = StreamDecoder.forInputStreamReader(in, this, (String)null);
        } catch (UnsupportedEncodingException e) {
            // The default encoding should always be available
            throw new Error(e);
        }
    }
     public InputStreamReader(InputStream in, String charsetName)
        throws UnsupportedEncodingException
    {
        super(in);
        if (charsetName == null)
            throw new NullPointerException("charsetName");
        sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
    }
     public InputStreamReader(InputStream in, Charset cs) {
        super(in);
        if (cs == null)
            throw new NullPointerException("charset");
        sd = StreamDecoder.forInputStreamReader(in, this, cs);
    }

  public int read(char cbuf[], int offset, int length) throws IOException {
        return sd.read(cbuf, offset, length);
    }
  public void close() throws IOException {
        sd.close();
    }
    //…(省略的代码)
 }
 /******************InputStream类(被适配类)******************/
 public abstract class InputStream implements Closeable {
 //代码省略
}

使用Demo

File file = new File("hello.txt");
FileInputStream in = new FileInputStream(file);
// 将FileInputStream适配成InputStreamReader,即输入的字节流转换成字符流
InputStreamReader inReader = new InputStreamReader(in);

总结

     适配器在IO中的应用就介绍到这里了,感谢您的耐心阅读!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奔跑的大白啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值