Android技术知识Android知识Android知识点和文章分享

设计模式-外观模式

2017-07-20  本文已影响55人  KevinLive

最近习惯了自己做饭,虽然做饭的过程很痛苦,可是看到自己做出来的美食后,还是很幸福很有成就感的。就拿自己做饭吃和去餐馆吃饭来举例,把餐馆看做外观角色,让它把买菜、切菜、炒菜、刷碗这些工作统一组织起来,我要做的就是告诉他要吃什么就行了,下面是示例代码:

SubSystem 类:

// 买菜
public class BuyVegetable {
    public void buy() {
        LogUtils.i("买菜");
    }
}

// 切菜
public class CutVegetable {
    public void cut() {
        LogUtils.i("切菜");
    }
}

// 炒菜
public class CookVegetable {
    public void cook() {
        LogUtils.i("炒菜");
    }
}

// 洗刷刷
public class WashDishes {
    public void wash() {
        LogUtils.i("洗刷刷");
    }
}

Facade 类:

// 餐馆
public class Restaurant {

    private final BuyVegetable mBuyVegetable;
    private final CutVegetable mCutVegetable;
    private final CookVegetable mCookVegetable;
    private final WashDishes mWashDishes;

    public Restaurant() {
        mBuyVegetable = new BuyVegetable();
        mCutVegetable = new CutVegetable();
        mCookVegetable = new CookVegetable();
        mWashDishes = new WashDishes();
    }

    public void eat() {
        mBuyVegetable.buy();
        mCutVegetable.cut();
        mCookVegetable.cook();
        mWashDishes.wash();
    }
}

Client 类:

// 自己做饭,需要跟这些子系统交互
BuyVegetable buyVegetable = new BuyVegetable();
CutVegetable cutVegetable = new CutVegetable();
CookVegetable cookVegetable = new CookVegetable();
WashDishes washDishes = new WashDishes();
buyVegetable.buy();
cutVegetable.cut();
cookVegetable.cook();
washDishes.wash();

// 去餐馆吃饭,只需跟餐馆交互
Restaurant restaurant = new Restaurant();
restaurant.eat();

有了外观模式,需要交互的类就变成了一个,让它负责和业务类实现交互,简化负责的交互,降低系统的耦合度,但是在标准的外观模式中,如果需要增删改外观类交互的子系统类,就需要改动客户端源码,这样就违反了“开闭原则”,因此遇到此类情况需要引入抽象外观类进行优化,还以上面例子为基础:

AbstarctFacade 类:

public abstract class AbstractFacade {
    public abstract void eat();
}

ConcreteFacade 类:

// 有些不用切就可以直接做的饭,比如面,这就需要把切菜移除掉
public class NoodlesRestaurant extends AbstractFacade{

    private final BuyVegetable mBuyVegetable;
    private final CookVegetable mCookVegetable;
    private final WashDishes mWashDishes;

    public NoodlesRestaurant() {
        mBuyVegetable = new BuyVegetable();
        mCookVegetable = new CookVegetable();
        mWashDishes = new WashDishes();
    }

    @Override
    public void eat() {
        mBuyVegetable.buy();
        mCookVegetable.cook();
        mWashDishes.wash();
    }
}

Client 类:

AbstractFacade abstractFacade = new NoodlesRestaurant();
abstractFacade.eat();

<h3> 优点 </h3>

<h3> 缺点 </h3>

<h3> 使用场景 </h3>

源码地址:Github

上一篇 下一篇

猜你喜欢

热点阅读