Decorator features:
1. The decorator and the decorator have the same supertype.
2. Inject the decorated object through the constructor.
3. The decorator can add its own behavior before and after the method being called by the decorator. This is somewhat similar to a static proxy.
In fact, the decorator design pattern is a method of enhancing classes with composition. Java io classes are heavily applied to the decorator pattern.
Code:
import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; public class MyFileInputStream extends FilterInputStream{ protected MyFileInputStream(InputStream in) { super(in); } @Override public int read() throws IOException { int i = super.read(); return i==-1?i:Character.toLowerCase((char)i); } @Override public int read(byte[] b, int off, int len) throws IOException { int re = super.read(b, off, len); for(int i=off;i<re+off;i++){ b[i] = (byte) Character.toLowerCase((char)b[i]); } return re; } }