[size=large]装饰者设计模式定义:动态的将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
[/size]
装饰者特点:
1、装饰着和被装饰着具有相同的超类型。
2、通过构造函数注入被装饰对象。
3、装饰者可以在被装饰者方法调用的前后加入自己的行为。这有点类似于静态代理。
实际上装饰者设计模式就是运用组合增强类的方法。java io类就大量应用到了装饰者模式。
代码:
[/size]
装饰者特点:
1、装饰着和被装饰着具有相同的超类型。
2、通过构造函数注入被装饰对象。
3、装饰者可以在被装饰者方法调用的前后加入自己的行为。这有点类似于静态代理。
实际上装饰者设计模式就是运用组合增强类的方法。java io类就大量应用到了装饰者模式。
代码:
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;
}
}