作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/
5.JDK中的装饰模式
最典型的就是IO系统了,比如BufferedInputStream及LineNumberInputStream都扩展自FilterInputStream——这个类是一个抽象的装饰类。而最高的抽象组件是InputStream类。
我们也可以以假乱真写一个输入流类
public class LowerCaseInputStream extends FilterInputStream {
public LowerCaseInputStream(InputStream in) {
super(in);
}
public int read() throws IOException {
int c = super.read();
return (c == -1 ? c : Character.toLowerCase((char)c));
}
public int read(byte[] b, int offset, int len) throws IOException {
int result = super.read(b, offset, len);
for (int i = offset; i < offset+result; i++) {
b[i] = (byte)Character.toLowerCase((char)b[i]);
}
return result;
}
}
public class InputTest {
public static void main(String[] args) throws IOException {
int c;
try {
InputStream in =
new LowerCaseInputStream(
new BufferedInputStream(
new FileInputStream("test.txt")));
while((c = in.read()) >= 0) {
System.out.print((char)c);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
6.装饰模式的一些缺陷:
产生各种小类,维护不便。有些代码会依赖特定的类型,而这样的代码一导入装饰者就出问题了。
总结:
装饰者模式动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案
FAQ:
为什么在一定要有Decorator这个类?
基于上边的这个例子我们可以看到Decorator这个类隔离了Component中可能出现的具体实现(比如上例中的getDescription方法),之所以要隔离室因为装饰者对这个方法的实现逻辑和高层的Component类实现的逻辑是不同的。在Decorator将一个方法退化为一个抽象方法,有助于督促具体的装饰器必须实现这个方法,而不会无意使用Component继承而来的方法(如果没有Decorator而直接继承自Component可能会因为实现逻辑不同而出现没有实现新逻辑而误用旧逻辑的情况,这会导致出现运行中错误,而退化为抽象方法后,具体装饰器则不得不实现这个方法,否则不可能编译通过,这就将错误压制在了编译阶段,显然,这相对于运行中出错是要好得多)。
作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/