和字面理解的差不多,装饰者模式就是用一个或多个类去扩展一个类的行为或状态,也就是扩展一个类的功能。相对于继承来说更加灵活。但要求装饰者和被装饰者要相同的超类型。
附上代码说明:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class UpperInputstream extends FilterInputStream {
public UpperInputstream(InputStream arg0) throws FileNotFoundException {
super(arg0);
}
//扩展父类的read()方法,使得读取后的字符自动转换为大写模式
public int read() throws IOException {
//通过filter的read()方法读取一个字节的数据
int c = super.read();
//如若不是结尾,则将数据转换为大写字母
return (c==-1?c:Character.toUpperCase(c));
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Test {
public static void main(String [] args) {
int c;
try {
//读取test文本的数据进行输出测试
InputStream in = new UpperInputstream(
new FileInputStream("test.txt"));
while((c = in.read())!= -1) {
System.out.print((char)c);
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
test文件:
测试结果:
--麦子