JDK源码解析 InputStream类就使用了模板方法模式
生活随笔
收集整理的這篇文章主要介紹了
JDK源码解析 InputStream类就使用了模板方法模式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
JDK源碼解析
InputStream類就使用了模板方法模式。
在InputStream類中定義了多個?read()?方法,如下:
public abstract class InputStream implements Closeable {//抽象方法,要求子類必須重寫public abstract int read() throws IOException; ?public int read(byte b[]) throws IOException {return read(b, 0, b.length);} ?public int read(byte b[], int off, int len) throws IOException {if (b == null) {throw new NullPointerException();} else if (off < 0 || len < 0 || len > b.length - off) {throw new IndexOutOfBoundsException();} else if (len == 0) {return 0;} ?int c = read(); //調(diào)用了無參的read方法,該方法是每次讀取一個字節(jié)數(shù)據(jù)if (c == -1) {return -1;}b[off] = (byte)c; ?int i = 1;try {for (; i < len ; i++) {c = read();if (c == -1) {break;}b[off + i] = (byte)c;}} catch (IOException ee) {}return i;} }從上面代碼可以看到,無參的?read()?方法是抽象方法,要求子類必須實現(xiàn)。
而?read(byte b[])?方法調(diào)用了?read(byte b[], int off, int len)?方法,
所以在此處重點看的方法是帶三個參數(shù)的方法。
在該方法中第18行、27行,可以看到調(diào)用了無參的抽象的?read()?方法。
總結(jié)如下: 在InputStream父類中已經(jīng)定義好了讀取一個字節(jié)數(shù)組數(shù)據(jù)的方法是每次讀取一個字節(jié),并將其存儲到數(shù)組的第一個索引位置,讀取len個字節(jié)數(shù)據(jù)。
具體如何讀取一個字節(jié)數(shù)據(jù)呢?由子類實現(xiàn)。
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的JDK源码解析 InputStream类就使用了模板方法模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JDK源码解析 Integer类使用了享
- 下一篇: JDK源码解析 Runable是一个典型