<分区>
这是 Head First 设计模式书中的一段代码片段:
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 Mocha extends CondimentDecorator {
Beverage beverage;
public Mocha(Beverage beverage) {
this.beverage = beverage;
}
public String getDescription() {
return beverage.getDescription() + ", Mocha";
}
public double cost() {
return .20 + beverage.cost();
}
}
这两个非常相似,只是 Macha 类内部有一个具体对象,它会初始化和使用,而 LowerCaseInputStream 类通过 super(in)
初始化 InputStream 对象,后来似乎使用使用 super.read()
函数读取此对象。
我对 super 函数在这里的工作方式有点困惑。在 Mocha 示例中,很明显它在内部包装了一个饮料对象并调用了它的方法并修改了结果,而在 LowerCaseInputStream 类中,行为修改是如何发生的并不直接。