定义
动态地给一个对象添加一些额外的职责,就增加功能来说,装饰者模式比生成子类更为灵活。——《设计模式:可复用面向对象软件的基础》
装饰者模式是一种对象结构型模式。
场景
在不影响其他对象的情况下,以动态、透明的方式给单个对象添加功能。
需要动态地给一个对象增加功能,这些功能也可以动态地被撤销。
在“类爆炸”情况下使用可减轻维护的类的数量(如java IO流使用)
优点:灵活,面向拓展开放,面向修改关闭,可以动态对类的功能进行“装饰”
缺点:代码书写增加了部分的复杂度,你可能会发现设计后会存在大量的小类,在使用的过程中你是否对Java IO的API使用带有困惑(当你想用缓冲的方式写入文件数据时小码农你是否有许多问号)

代码示例
package com.example.demo.design.decorator;
import java.io.*;
public class LowerCaseInputStream extends FilterInputStream {
public LowerCaseInputStream(InputStream inputStream) {
super(inputStream);
}
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 static void main(String[] args) {
int c;
try {
InputStream in = new LowerCaseInputStream(new BufferedInputStream(new FileInputStream("D:\\project\\demo\\src\\main\\java\\com\\example\\demo\\design\\decorator\\test.txt")));
while ((c = in.read()) >= 0) {
System.out.print((char)c);
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
总结
其实装饰者只是在各种使用场景下使用合适的类,你可以根据你的需要去“装饰”。比如Java的所有IO相关的类,本质都是为了InputStream和OutputStream服务,只不过在你使用的时候如果不熟悉的话会无从下手。但是,如此的灵活总得有他的代价不是吗!