设计模式之装饰者(java)

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

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

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

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

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();
        }
    }
}

运行结果:
运行截图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值