(十)装饰器模式详解(与IO不解的情缘)

LZ到目前已经写了九个设计模式,回过去看看,貌似写的有点凌乱,LZ后面会尽可能改进。java

                 那么本章LZ和各位读友讨论一个与JAVA中IO有着不解情缘的设计模式,装饰器模式。web

                 定义:装饰模式是在没必要改变原类文件和使用继承的状况下,动态的扩展一个对象的功能。它是经过建立一个包装对象,也就是装饰来包裹真实的对象。算法

                 这一个解释,引自百度百科,咱们注意其中的几点。设计模式

                 1,不改变原类文件。数组

                 2,不使用继承。app

                 3,动态扩展。eclipse

                 上述三句话一语道出了装饰器模式的特色,下面LZ给出装饰器模式的类图,先上图再解释。oop


                  从图中能够看到,咱们装饰的是一个接口的任何实现类,而这些实现类也包括了装饰器自己,装饰器自己也能够再被装饰。测试

                  另外,这个类图只是装饰器模式的完整结构,但其实里面有不少能够变化的地方,LZ给出以下两条。this

                  1,Component接口能够是接口也能够是抽象类,甚至是一个普通的父类(这个强烈不推荐,普通的类做为继承体系的超级父类不易于维护)。

                  2,装饰器的抽象父类Decorator并非必须的。

                 那么咱们将上述标准的装饰器模式,用咱们熟悉的JAVA代码给诠释一下。首先是待装饰的接口Component。

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_1 name=ZeroClipboardMovie_1 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=1&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. package com.decorator;  

  2.   

  3. public interface Component {  

  4.   

  5.     void method();  

  6.       

  7. }  

                 接下来即是咱们的一个具体的接口实现类,也就是俗称的原始对象,或者说待装饰对象。

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_2 name=ZeroClipboardMovie_2 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=2&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. package com.decorator;  

  2.   

  3. public class ConcreteComponent implements Component{  

  4.   

  5.     public void method() {  

  6.         System.out.println("原来的方法");  

  7.     }  

  8.   

  9. }  

                 下面即是咱们的抽象装饰器父类,它主要是为装饰器定义了咱们须要装饰的目标是什么,并对Component进行了基础的装饰。

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_3 name=ZeroClipboardMovie_3 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=3&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. package com.decorator;  

  2.   

  3. public abstract class Decorator implements Component{  

  4.   

  5.     protected Component component;  

  6.   

  7.     public Decorator(Component component) {  

  8.         super();  

  9.         this.component = component;  

  10.     }  

  11.   

  12.     public void method() {  

  13.         component.method();  

  14.     }  

  15.       

  16. }  

                  再来即是咱们具体的装饰器A和装饰器B。

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_4 name=ZeroClipboardMovie_4 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=4&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. package com.decorator;  

  2.   

  3. public class ConcreteDecoratorA extends Decorator{  

  4.   

  5.     public ConcreteDecoratorA(Component component) {  

  6.         super(component);  

  7.     }  

  8.       

  9.     public void methodA(){  

  10.         System.out.println("被装饰器A扩展的功能");  

  11.     }  

  12.   

  13.     public void method(){  

  14.         System.out.println("针对该方法加一层A包装");  

  15.         super.method();  

  16.         System.out.println("A包装结束");  

  17.     }  

  18. }  

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_5 name=ZeroClipboardMovie_5 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=5&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. package com.decorator;  

  2.   

  3. public class ConcreteDecoratorB extends Decorator{  

  4.   

  5.     public ConcreteDecoratorB(Component component) {  

  6.         super(component);  

  7.     }  

  8.       

  9.     public void methodB(){  

  10.         System.out.println("被装饰器B扩展的功能");  

  11.     }  

  12.   

  13.     public void method(){  

  14.         System.out.println("针对该方法加一层B包装");  

  15.         super.method();  

  16.         System.out.println("B包装结束");  

  17.     }  

  18. }  

                下面给出咱们的测试类。咱们针对多种状况进行包装。

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_6 name=ZeroClipboardMovie_6 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=6&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. package com.decorator;  

  2.   

  3. public class Main {  

  4.   

  5.     public static void main(String[] args) {  

  6.         Component component =new ConcreteComponent();//原来的对象  

  7.         System.out.println("------------------------------");  

  8.         component.method();//原来的方法  

  9.         ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(component);//装饰成A  

  10.         System.out.println("------------------------------");  

  11.         concreteDecoratorA.method();//原来的方法  

  12.         concreteDecoratorA.methodA();//装饰成A之后新增的方法  

  13.         ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB(component);//装饰成B  

  14.         System.out.println("------------------------------");  

  15.         concreteDecoratorB.method();//原来的方法  

  16.         concreteDecoratorB.methodB();//装饰成B之后新增的方法  

  17.         concreteDecoratorB = new ConcreteDecoratorB(concreteDecoratorA);//装饰成A之后再装饰成B  

  18.         System.out.println("------------------------------");  

  19.         concreteDecoratorB.method();//原来的方法  

  20.         concreteDecoratorB.methodB();//装饰成B之后新增的方法  

  21.     }  

  22. }  

                 下面看下咱们运行的结果,究竟是产生了什么效果。

               今后能够看到,咱们首先是使用的原始的类的方法,而后分别让A和B装饰完之后再调用,最后咱们将两个装饰器一块儿使用,再调用该接口定义的方法。

               上述当中,咱们分别对待装饰类进行了原方法的装饰和新功能的增长,methodA和methodB就是新增长的功能,这些都是装饰器能够作的,固然二者并不必定兼有,但通常至少会有一种,不然也就失去了装饰的意义。

               另外,文章开篇就说道了IO与装饰器的情缘,相信各位就算不太清楚,也都大体据说过JAVA的IO是装饰器模式实现的,因此LZ也再也不废话,在给出一个标准的模板示例之后,直接拿出IO的示例,咱们真枪实弹的来。

               下面LZ直接给出IO包中的部分装饰过程,上面LZ加了详细的注释以及各个装饰器的功能演示,各位能够和上面标准的装饰器模式对比一下,LZ不得不感叹,IO与装饰器的孽缘。

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_7 name=ZeroClipboardMovie_7 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=7&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. package com.decorator;  

  2.   

  3. import java.io.BufferedInputStream;  

  4. import java.io.BufferedReader;  

  5. import java.io.DataInputStream;  

  6. import java.io.FileInputStream;  

  7. import java.io.IOException;  

  8. import java.io.InputStream;  

  9. import java.io.InputStreamReader;  

  10. import java.io.LineNumberReader;  

  11. import java.io.PushbackInputStream;  

  12. import java.io.PushbackReader;  

  13.   

  14. public class IOTest {  

  15.   

  16.     /* test.txt内容: 

  17.      * hello world! 

  18.      */  

  19.     public static void main(String[] args) throws IOException, ClassNotFoundException {  

  20.         //文件路径可自行更换  

  21.         final String filePath = "E:/myeclipse project/POITest/src/com/decorator/test.txt";  

  22.           

  23.         //InputStream至关于被装饰的接口或者抽象类,FileInputStream至关于原始的待装饰的对象,FileInputStream没法装饰InputStream  

  24.         //另外FileInputStream是以只读方式打开了一个文件,并打开了一个文件的句柄存放在FileDescriptor对象的handle属性  

  25.         //因此下面有关回退和从新标记等操做,都是在堆中创建缓冲区所形成的假象,并非真正的文件流在回退或者从新标记  

  26.         InputStream inputStream = new FileInputStream(filePath);  

  27.         final int len = inputStream.available();//记录一下流的长度  

  28.         System.out.println("FileInputStream不支持mark和reset:" + inputStream.markSupported());  

  29.           

  30.         System.out.println("---------------------------------------------------------------------------------");  

  31.           

  32.         /* 下面分别展现三种装饰器的做用BufferedInputStream,DataInputStream,PushbackInputStream,LZ下面作了三个装饰器的功能演示  */  

  33.           

  34.         //首先装饰成BufferedInputStream,它提供咱们mark,reset的功能  

  35.         BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);//装饰成 BufferedInputStream  

  36.         System.out.println("BufferedInputStream支持mark和reset:" + bufferedInputStream.markSupported());  

  37.         bufferedInputStream.mark(0);//标记一下  

  38.         char c = (char) bufferedInputStream.read();  

  39.         System.out.println("LZ文件的第一个字符:" + c);  

  40.         bufferedInputStream.reset();//重置  

  41.         c = (char) bufferedInputStream.read();//再读  

  42.         System.out.println("重置之后再读一个字符,依然会是第一个字符:" + c);  

  43.         bufferedInputStream.reset();  

  44.           

  45.         System.out.println("---------------------------------------------------------------------------------");  

  46.           

  47.         //装饰成 DataInputStream,咱们为了又使用DataInputStream,又使用BufferedInputStream的mark reset功能,因此咱们再进行一层包装  

  48.         //注意,这里若是不使用BufferedInputStream,而使用原始的InputStream,read方法返回的结果会是-1,即已经读取结束  

  49.         //由于BufferedInputStream已经将文本的内容读取完毕,并缓冲到堆上,默认的初始缓冲区大小是8192B  

  50.         DataInputStream dataInputStream = new DataInputStream(bufferedInputStream);  

  51.         dataInputStream.reset();//这是BufferedInputStream提供的功能,若是不在这个基础上包装会出错  

  52.         System.out.println("DataInputStream如今具备readInt,readChar,readUTF等功能");  

  53.         int value = dataInputStream.readInt();//读出来一个int,包含四个字节  

  54.         //咱们转换成字符依次显示出来,能够看到LZ文件的前四个字符  

  55.         String binary = Integer.toBinaryString(value);  

  56.         int first = binary.length() % 8;  

  57.         System.out.print("使用readInt读取的前四个字符:");  

  58.         for (int i = 0; i < 4; i++) {  

  59.             if (i == 0) {  

  60.                 System.out.print(((char)Integer.valueOf(binary.substring(0, first), 2).intValue()));  

  61.             }else {  

  62.                 System.out.print(((char)Integer.valueOf(binary.substring(( i - 1 ) * 8 + first, i * 8 + first), 2).intValue()));  

  63.             }  

  64.         }  

  65.         System.out.println();  

  66.           

  67.         System.out.println("---------------------------------------------------------------------------------");  

  68.           

  69.         //PushbackInputStream没法包装BufferedInputStream支持mark reset,由于它覆盖了reset和mark方法  

  70.         //由于流已经被读取到末尾,因此咱们必须从新打开一个文件的句柄,即FileInputStream  

  71.         inputStream = new FileInputStream(filePath);  

  72.         PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream,len);//装饰成 PushbackInputStream  

  73.         System.out.println("PushbackInputStream装饰之后支持退回操做unread");  

  74.         byte[] bytes = new byte[len];  

  75.         pushbackInputStream.read(bytes);//读完了整个流  

  76.         System.out.println("unread回退前的内容:" + new String(bytes));  

  77.         pushbackInputStream.unread(bytes);//再退回去  

  78.         bytes = new byte[len];//清空byte数组  

  79.         pushbackInputStream.read(bytes);//再读  

  80.         System.out.println("unread回退后的内容:" + new String(bytes));  

  81.           

  82.         System.out.println("---------------------------------------------------------------------------------");  

  83.           

  84.         /*  以上有两个一层装饰和一个两层装饰,下面咱们先装饰成Reader,再进行其它装饰   */  

  85.           

  86.         //因为以前被PushbackInputStream将流读取到末尾,咱们须要再次从新打开文件句柄  

  87.         inputStream = new FileInputStream(filePath);  

  88.         InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");//先装饰成InputStreamReader  

  89.         System.out.println("InputStreamReader有reader的功能,好比转码:" + inputStreamReader.getEncoding());  

  90.           

  91.         System.out.println("---------------------------------------------------------------------------------");  

  92.           

  93.         BufferedReader bufferedReader = new BufferedReader(inputStreamReader);//咱们进一步在reader的基础上装饰成BufferedReader  

  94.         System.out.println("BufferedReader有readLine等功能:" + bufferedReader.readLine());  

  95.           

  96.         System.out.println("---------------------------------------------------------------------------------");  

  97.           

  98.         LineNumberReader lineNumberReader = new LineNumberReader(inputStreamReader);//咱们进一步在reader的基础上装饰成LineNumberReader  

  99.         System.out.println("LineNumberReader有设置行号,获取行号等功能(行号从0开始),当前行号:" + lineNumberReader.getLineNumber());  

  100.           

  101.         System.out.println("---------------------------------------------------------------------------------");  

  102.           

  103.         //此处因为刚才被readLine方法将流读取到末尾,因此咱们再次从新打开文件句柄,并须要将inputstream再次包装成reader  

  104.         inputStreamReader = new InputStreamReader(new FileInputStream(filePath));  

  105.         PushbackReader pushbackReader = new PushbackReader(inputStreamReader,len);//咱们进一步在reader的基础上装饰成PushbackReader  

  106.         System.out.println("PushbackReader是拥有退回操做的reader对象");  

  107.         char[] chars = new char[len];  

  108.         pushbackReader.read(chars);  

  109.         System.out.println("unread回退前的内容:" + new String(chars));  

  110.         pushbackReader.unread(chars);//再退回去  

  111.         chars = new char[len];//清空char数组  

  112.         pushbackReader.read(chars);//再读  

  113.         System.out.println("unread回退后的内容:" + new String(chars));  

  114.     }  

  115. }  

                     上述即是IO的装饰器使用,其中InputStream就至关于上述的Component接口,只不过这里是一个抽象类,这是咱们装饰的目标抽象类。FileInputstream就是一个ConcreteComponent,即待装饰的具体对象,它并非JAVA的IO结构中的一个装饰器,由于它没法装饰InputStream。剩下BufferedInputStream,DataInputstream等等就是各类装饰器了,对比上述的标准装饰器样板,JAVA的IO中也有抽象的装饰器基类的存在,只是上述没有体现出来,就是FilterInputStream,它是不少装饰器最基础的装饰基类。

                     在上述过程当中,其中dataInputStream是通过两次装饰后获得的,它具备了dataInputStream和bufferedInputStream的双重功能,另外,InputStreamReader是一个特殊的装饰器,它提供了字节流到字符流的桥梁,其实它除了具备装饰器的特色之外,也有点像一个适配器,但LZ仍是以为它应当算是一个装饰器。

                    其它的IO装饰器各位能够自行尝试或者和上述的标准的装饰器模式代码比对一下,下面另附LZ的IO装饰器程序运行后结果。

                     从上面的展现中,已经能够充分体会到装饰器模式的灵活了,咱们建立的一个FileInputstream对象,咱们可使用各类装饰器让它具备不一样的特别的功能,这正是动态扩展一个类的功能的最佳体现,而装饰器模式的灵活性正是JAVA中IO所须要的,不得不赞一下JAVA类库的建造者实在是强悍。

                     上述的XXXXInputStream的各个类都继承了InputStream,这样作不只是为了复用InputStream的父类功能(InputStream也是一种模板方法模式,它定义了read(byte[])方法的简单算法,并将read()方法交给具体的InputStream去实现),也是为了能够重叠装饰,即装饰器也能够再次被装饰,而过渡到Reader之后,Reader的装饰器体系则是相似的。

                     下面LZ给出上面IO包中所涉及的类的类图,各位能够自行和上面的标准装饰器模式对比一下。


                     LZ在类图上标注了各个类负责的角色,而且使用背景颜色将InputStream和Reader体系分开,其中左半部分就是InputStream的装饰体系,右半部分就是Reader的装饰体系,而且他们之间的桥梁是InputStreamReader,他们每个装饰体系都与上面标准的装饰器模式类图极其类似,各位能够本身看一下,感觉一下,尤为是InputStreamReader,它的位置比较特殊。

                     总之呢,装饰器模式就是一个能够很是灵活的动态扩展类功能的设计模式,它采用组合的方式取代继承,使得各个功能的扩展更加独立和灵活。

                     本次装饰器模式就到此结束了,感谢各位的收看,下期再见。

                     下期预告,外观模式。   

相关文章
相关标签/搜索