设计模式之装饰者(java)

来源:互联网 发布:stm32与51单片机区别 编辑:程序博客网 时间:2024/06/05 06:17

装饰者模式其是一种使用组合或者委托的方式对某种类进行进一步包装,避免直接全部使用继承实现很多的时候而显得非常臃肿。

当你不想对原来的类结构做出改变,你又想给原来的类添加功能,你有可能就直接继承原来的类,这样做的问题是当需要很多功能添加的时候需要很多继承类,后期的维护会变的很困难,这就是所谓的“类爆炸”。

所以使用装饰者模式是一个相对较好的方式在原功能类添加功能(不需要对原来的类结构做出改变),当然装饰者模式也有它不好的地方。

下面看一个例子会理解的更透彻:
定义装饰者类:

public class LowerCaseInputStream extends FilterInputStream {    public LowerCaseInputStream(InputStream in) throws IOException {        super(in);    }    public int read() throws IOException {        int c = super.read();        return (c == -1 ? c : Character.toLowerCase((char)c));    }    public int read(byte[] b, int offset, int len) throws IOException {        int result = super.read(b, offset, len);        for (int i=offset; i<offset+result; i++) {            b[i] = (byte) Character.toLowerCase((char)b[i]);        }        return result;    }}

测试刚才的装饰类:

public class InputTest {    public static void main(String[] args) throws IOException {        int c;        try{            InputStream in = new LowerCaseInputStream(                    new BufferedInputStream(                            new FileInputStream("E://test.txt")));            while ((c = in.read()) >= 0) {                System.out.print((char) c);            }            in.close();        } catch (Exception e) {            e.printStackTrace();        }    }}

运行结果:
运行截图

0 0
原创粉丝点击