装饰者模式

装饰者模式>>>动态地将责任附加到对象上  若要扩展功能,提供了比继承更有弹性的替代方案,那就是组合。

 

这也满足了高效java推荐的方法:尽量用组合来替代继承 

 

装饰者和被装饰者(即被包装的组件)必须是一样的类型,也就是说有共同的超类,为什么呢,因为装饰者必须能取代被装饰者

 

Java/Io系统就是一个典型的装饰器模式

   装饰组件是InputStream  装饰器FilterInputStream  如果要扩展 只需要继承FilterInputStream 重写read()方法就行了

 

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class LowerCaseInputStream extends FilterInputStream{

    protected LowerCaseInputStream(InputStream in) {
        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 length) throws IOException{
        int result = super.read(b, offset, length);
        for(int i = offset ; i < offset + result ;  i ++) {
            b[i] = (byte)Character.toLowerCase((char)b[i]);
        }
        return result;
    }
   
    public static void main(String[] args) {
        int c ;
        try {
            //一层层的装饰
            InputStream in = new LowerCaseInputStream(
                    new BufferedInputStream(new FileInputStream("D://test.txt")));
            while((c = in.read()) >= 0 ) {
                System.out.println((char)c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值