java设计模式之------装饰者模式
============================================
装饰模式(Decorator),动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
可以有效的把类的核心职责和装饰功能区分开。
Cooking炒菜
CookingEgg炒鸡蛋
Condimen调料基类(只是抽象了一层行为,跟装饰者模式没关系)
Oil油
Salt盐
abstract class Cooking {
public abstract void doCooking();
}
public class CookingEgg extends Cooking {
public void doCooking(){
System.out.println("do Egg Cooking");
}
}
public abstract class Condimen extends Cooking {
public abstract void doCooking();
}
public class Oil extends Condimen {
Cooking cooking;
public Oil(Cooking cooking){
this.cooking = cooking;
}
public void doCooking(){
cooking.doCooking();
//一些功能扩展
System.out.println("add Oil");
}
}
public class Salt extends Condimen {
Cooking cooking;
public Salt(Cooking cooking){
this.cooking = cooking;
}
public void doCooking(){
cooking.doCooking();
//一些功能扩展
System.out.println("add Salt");
}
}
public abstract class Test {
public static void main(String[] args) {
Cooking cooking = new CookingEgg();
Oil oil = new Oil(cooking);
Salt salt = new Salt(oil);
salt.doCooking();
//addCondimen("Oil");
//addCondimen("Salt");
addCondimen("OilSalt");
}
public static void addCondimen(String condimen) {
Cooking cooking = new CookingEgg();
if(condimen.contains("Oil")){
cooking = new Oil(cooking);
}
if(condimen.contains("Salt")){
cooking = new Salt(cooking);
}
cooking.doCooking();
}
}
Mybatis缓存设计和I/O流的设计,就是应用装饰者模式思想设计的
1.Mybatis缓存设计
Executor执行类
public Executor newExecutor(Transaction transaction, ExecutorType executorType, boolean autoCommit) {
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor, autoCommit);//装饰
}
return executor;
}
结构类图:
executor.query()[BaseExecutor.query()-->SimpleExecutor.doQuery()]
executor.query()[CachingExecutor.query()-->BaseExecutor.query()-->SimpleExecutor.doQuery()]
CachingExecutor包装BaseExecutor
2.I/O流