decorator(装饰模式)io包理解

decorator的结构如下:

MyInterface
|
_______|_______
| |
Myclass Decorator
____|_____
| |
DecoratorA DecoratorB
decorator的目的是在不改变基础类的前提下,添加新的功能(在比较少的子类前提),Myclass是你的扩展类,decoratorA,decoratorB封装了你要扩展的功能,并保持了 MyInterface的引用

考虑一下代码
public static void main(String[]args){
MyInterface a=new Myclass();
a.print();
}
MyInterface是Myclass的接口,在 MyInterface里面就声明了一个print方法,myclass实现了该方法
public void print(){
System.out.print("hello");
}
如果我们要实现打印 ”hello word“,”my hell“就要要写很多类似的类,

decorator装饰模式的解决方法就是,只实现基本功能,附加功能都抽出来,
public decoratorA implements Decorator{
MyInterface myObject;
public decoratorA(MyInterface my){
myObject=my;
}
public void print(){
System.out.print(" world ");
}

}

public decoratorB implements Decorator{
MyInterface myObject;
public decoratorB(MyInterface my){
myObject=my;
}
public void print(){
System.out.print("MY ");
myObject.print();
}

}
这时需要实现my hello word就比较简单了
public void main(String[]args){
MyInterface a=new decoratorA (new decoratorB(new Myclass()) );
a.print();
}

BufferedInputStream bis = new BufferedInputStream(new DataInpuStream(new FileInputStream("xxx.txt")));

InputStream.为例:
java.io.InputStream
|
_______________________|________________________
| |
ByteArrayInputStream FilterInputStream
StringBufferInputStream _____________________|____________________________
FileInputStream | | | |
PipedInputStream DataInputStream BufferedInputStream LineNumInpuStream PushbackInputStream

基础的流只有左边4个,这些流代表了数据的来源,所有的流都必须从这四个中之一开始(注,还有一个RandomAccessFile、File,这两个不在本文介绍范围)。
当我们需要什么新功能的时候就在右边找个装饰类,在用到缓存的时候我们就用bufferedInputStream

BufferdInputStream is = new BufferedInputStream(new FileInputStream("xxx.txt"));


假如再要DataInputStream的功能,只要在加一层:
DataInputStream dis = new DataInputStream(new BufferdInputStream(new FileInputStream));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值