FilterInputStream之装饰模式(例)

来源:互联网 发布:王坚 阿里云 编辑:程序博客网 时间:2024/06/12 20:30

FilterInputStream之装饰模式


1.装饰模式

概诉:
允许向一个现有的对象添加新的功能,同时不改变其结构
属于结构型模式,作为现有类的一个包装
原理
1.1 增加一个修饰类包裹原来的类 —— 包裹的方式一般是通过在将原来的对象作为修饰类的构造函数的参数实现装饰类实现新的功能,
1.2 在不需要用到新功能的地方,它可以直接调用原来的类中的方法。
1.3 修饰类必须和原来的类有相同的接口。


2. 利用FilterInputStream实现大小写字母转化(例)

2.1 首先我们创建一个我们自定义的FilterInputStream的子类UpperCaseInputStream,重写其red()方法来实现我们的需求,请看以下代码:

UpperCaseInputStream 类

import java.io.FilterInputStream;import java.io.IOException;import java.io.InputStream;//创建UpperCaseInputStream 类继承于FilterInputStream public class UpperCaseInputStream extends FilterInputStream {    //构造方法    protected UpperCaseInputStream(InputStream in) {        super(in);    }    /**     * 重写red()方法     */    @Override    public int read() throws IOException {        int c = super.read();        return c == -1 ? c : Character.toUpperCase((char) c);//判断取出的字符是否小写,如果是,则进行装换    }    /**     * 重写read(byte[] b, int off, int len)方法     */    @Override    public int read(byte[] b, int off, int len) throws IOException {        int length = super.read(b, off, len);        for (int i = 0; i < length; i++) {            b[i] = (byte) Character.toUpperCase((char) b[i]);        }        return length;    }}

main类

import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.Writer;public class Hw {    public static void main(String[] args) {        try {            File file = new File("test.txt");            if(!file.exists()){                file.createNewFile();            }            Writer w = new FileWriter(file);            w.write("dhflHKLAGhkLHKhl");            w.flush();              InputStream is = new UpperCaseInputStream(new FileInputStream("test.txt"));            int c;            while ((c = is.read()) != -1) {                System.out.print((char) c);            }            is.close();            w.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}