package com.czie.d4_decorator_pattern; /** 装饰模式 定义父类:InputStream 定义实现类:FileInputStream 继续父类 定义功能 定义装饰实现类:BufferedInputStream 继承父类 定义功能 包装原始类,增强功能。 */ public class DecoratorPattern { public static void main(String[] args) { InputStream is = new BufferedInputStream(new FileInputStream()); System.out.println(is.read()); System.out.println(is.read(new byte[3])); } }
package com.czie.d4_decorator_pattern; /** 装饰类:继承InputStream 拓展原始类的功能 */ public class BufferedInputStream extends InputStream { private InputStream is; public BufferedInputStream(InputStream is){ this.is=is; } @Override public int read() { System.out.println("提供8KB的缓冲区,提高读数据性能~~~~"); return is.read(); } @Override public int read(byte[] buffer) { System.out.println("提供8KB的缓冲区,提高读数据性能~~~~"); return is.read(buffer); } }
package com.czie.d4_decorator_pattern; /** 共同父类 */ public abstract class InputStream{ public abstract int read() ; public abstract int read(byte[] buffer) ; }
package com.czie.d4_decorator_pattern; import java.util.Arrays; /** 原始类 */ public class FileInputStream extends InputStream { @Override public int read() { System.out.println("低性能的方式读取了一个字节a"); return 97; } @Override public int read(byte[] buffer) { buffer[0] = 97; buffer[1] = 98; buffer[2] = 99; System.out.println("低性能的方式读取了一个字节数组:" + Arrays.toString(buffer)); return 3; } }