ITeye博客

decorator(装饰模式)io包理解

iehyou · 2010-03-30 16:01 · J2EE · 编程语言 · 数据结构 · Markdown

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)

暂无评论。

评论功能维护中,当前仅展示历史评论。