设计模式(4)--装饰者模式

    xiaoxiao2021-03-25  141

    一、装饰者模式定义 装饰者模式:动态地将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案。 设计原则:对扩展开放,对修改关闭。 二、装饰者模式代码实例 Java.io包内的类就是装饰者模式的最好体现,所以下面以编写一个装饰者,把输入流内的所有大写字符转成小写。

    package Model; import java.io.*; /** * Created by L_kanglin on 2017/3/8. */ public class InputTest { public static void main(String[] args) throws IOException { int c; InputStream in = null; try { //设置FileInputStream,先用BufferedInputStream装饰它,再用我们崭新的LowerCaseInputStream过滤器装饰它 in = new LowerCaseInputStream(new BufferedInputStream(new FileInputStream("C:\\Users\\PVer\\IdeaProjects\\program\\src\\Model\\test.txt"))); while((c= in.read())>=0){ System.out.print((char)c); } in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } import java.io.InputStream; /** * Created by L_kanglin on 2017/3/8. * 编写一个装饰者,把输入流内的所有大写字符转换为小写字符 */ //扩展FilterInputStream,这是所有InputStream的抽象装饰者 public class LowerCaseInputStream extends FilterInputStream { public LowerCaseInputStream(InputStream in) { super(in); } //重写read方法 @Override public int read() throws IOException { int c= super.read(); return (c== -1 ? c:Character.toLowerCase((char) c)); } @Override public int read(byte[] b, int off, int len) throws IOException { int result=super.read(b, off, len); for(int i=off;i< off+result;i++){ b[i]=(byte)Character.toLowerCase((char)b[i]); } return result; } }

    运行结果如下:

    i know the pattern

    三、装饰者模式分析 (1)装饰者和被装饰者必须是一样的类型,也就是有共同的超类,在这里,我利用继承达到“类型匹配”,而不是利用继承获得“行为”。上述实例中,LowerCaseInputStream、BufferedInputStream和FileInputStream都是拥有FileInputStream这个超类,而InputStream则是我们得抽象组件; (2)可以用一个或多个装饰者对象包装一个对象; (3)既然装饰者和被装饰者对象有相同的超类型,所以在任何时候需要原始对象(被包装的)的场合,可以用装饰过的对象代替它; (4)装饰者可以在所委托被装饰者的行为之前或之后,加上自己的行为,以达到特定的目的。 (5)对象可以在任何时候被装饰,所以可以在运行时动态的、不限量的用你喜欢的装饰者来装饰对象。

    文章只是作为自己的学习笔记,借鉴了网上的许多案例,如果觉得阔以的话,希望多交流,在此谢过…

    转载请注明原文地址: https://ju.6miu.com/read-6661.html

    最新回复(0)