随笔 - 31  文章 - 2  trackbacks - 0
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));




















posted on 2008-04-20 11:35 缘来如此 阅读(334) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: