装饰器模式,最经典的使用应该是在java的读写类中了,用比喻来说,decorator就是一列或者,每一节都增强一节功能。
例子
public abstract class InputStream implements Closeable {
public abstract int read() throws IOException;
public int read(byte[] b) throws IOException {
return this.read(b, 0, b.length);
}
public class FileInputStream extends InputStream {
public FileInputStream(String name) throws FileNotFoundException
public FileInputStream(File file) throws FileNotFoundException
private native int readBytes(byte[] var1, int var2, int var3) throws IOException;
public int read(byte[] b) throws IOException {
return this.readBytes(b, 0, b.length);
}
public int read(byte[] b, int off, int len) throws IOException {
return this.readBytes(b, off, len);
}
}
public class FilterInputStream extends InputStream {
protected volatile InputStream in;
protected FilterInputStream(InputStream in) {
this.in = in;
}
public int read() throws IOException {
return this.in.read();
}
public int read(byte[] b) throws IOException {
return this.read(b, 0, b.length);
}
public int read(byte[] b, int off, int len) throws IOException {
return this.in.read(b, off, len);
}
}
从上面例子可以看到, FilterInputStream中可以使用基础的InputStream,并且在FilterInputStream中增强功能使用。具体的增强使用要看FilterInputStream的继承类BufferedInputStream。
vs Proxy模式
上面的代码让人心生疑惑,这和proxy有什么不同,实现上唯一的不同就是这是一列或者,可以无限的decorator下去。但是其实从代码上看也没有什么不同,代理类也是这么写的,怎么理解呢?
这就要从场景上理解了,decorator是为了在原有的功能上增强,而proxy模式是为了将额外工作转包给代理类,然给开发人员聚焦在业务逻辑上。
小结
理解设计模式,还是要从其应用的场景上来理解,否则可能左看右看,长相一样,不明觉厉。
网友评论