装饰者模式
动态地将责任附加到对象上,若要有扩展功能,装饰者提供了比继承有弹性的替代方案。
类图
应用
例子
咖啡类,可以加调料,计算价格
想法
设计
代码示例
public class Mocha extends CondimentDecorator{
Beverage beverage;
public Mocha(Beverage beverage){
this.beverage = beverage;
}
public String getDescription(){
return beverage.description + " Mocha";
}
public double cost(){
return .2+beverage.cost();
}
}
JDK中的装饰者模式
java.io类
正常应用
自己写一个
public class LowerCaseInputStream extends FilterInputStream {
/**
* Creates a <code>FilterInputStream</code>
* by assigning the argument <code>in</code>
* to the field <code>this.in</code> so as
* to remember it for later use.
*
* @param in the underlying input stream, or <code>null</code> if
* this instance is to be created without an underlying stream.
*/
protected LowerCaseInputStream(InputStream in) {
super(in);
}
//读取当前流中的下一个字节、并以整数形式返回、若读取到文件结尾则返回-1。
public int read() throws IOException {
int c = super.read();
return c==-1?c:Character.toLowerCase(c);
}
//将当前流中的len个字节读取到从下标off开始存放的字节数组b中。
public int read(byte b[], int off, int len) throws IOException {
int res = super.read(b,off,len);
for(int i = off;i<off+res;i++){
b[i] = (byte)Character.toLowerCase(b[i]);
}
return res;
}
}
测试
public class InputTest {
public static void main(String[] args) {
int c;
try {
InputStream in = new LowerCaseInputStream(new BufferedInputStream(new ByteArrayInputStream("HAHAHAH".getBytes())));
while ((c=in.read())>=0){
System.out.print((char)c);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
输出hahahah