Here is a code snippet from the head first design patterns book:
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;
}
}
There is another toy example in the same chapter:
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();
}
}
These two are quite similar except that the Macha class has a concrete object inside that it initialize and use, while the LowerCaseInputStream class initializes an InputStream object by super(in)
and later seems to make use of this object by using the super.read()
function.
I am a bit confused about how the super function works here. In the Mocha example, it's very clear that it wraps a beverage object inside and calls its methods and modifies the results, while in the LowerCaseInputStream class it's not straight-forward how the behavior modification happened.