-
动态地给一个对象添加一些额外的职责。就增加功能来说, Decorator模式相比生成子类更为灵活。该模式以对客 户端透明的方式扩展对象的功能。(组合优先于继承)
-
1.Component(被装饰对象的接口)
定义一个对象接口,可以给这些对象动态地添加职责。
2.ConcreteComponent(具体被装饰对象)
定义一个对象,可以给这个对象添加一些职责。
3.Decorator(装饰者抽象类)
维持一个指向Component实例的引用,并定义一个与Component接口一致的接口。
4.ConcreteDecorator(具体装饰者)
具体的装饰对象,给内部持有的具体被装饰对象,增加具体的职责。当然3和4可以只有一个普通类
-
Mybatis中装饰者应用Cache
1.接口
public interface Cache {
String getId();
int getSize();
void putObject(Object key, Object value);
Object getObject(Object key);
Object removeObject(Object key);
void clear();
ReadWriteLock getReadWriteLock();
}
2.唯一基础实现类
public class PerpetualCache implements Cache {
}
3.装饰器
public class LruCache implements Cache {
private final Cache delegate;//依赖-持有接口对象
public LruCache(Cache delegate) { //依赖基础对象来构造装饰器
this.delegate = delegate;
setSize(1024);
}
}
Mybatis提供了8个装饰器
同样在JAVA的IO类中,也使用了装饰者模式:
InputStream就是装饰者模式中的接口超类(Component)
ByteArrayInputStream,FileInputStream相当于被装饰者(ConcreteComponent),这些类都提供了最基本的字节读取功能。
FilterInputStream即是装饰者(Decorator),BufferedInputStream,DataInputStream,PushbackInputStream
根据装饰者模式的特点,所有我们在使用BufferedInputStream需要传入inputstream对象;