java设计模式之------装饰者模式


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流



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值