门面模式-Facade Pattern(Java实现)
门面模式-Facade Pattern
为一个复杂的模块或子系统提供一个简单的供外界访问的接口
本文中代码的例子如下: 一个矿场有很多矿工, 矿工的职责也都不一样. 但一样的是什么呢? 一样的就是每个矿工每天都在重复一样的事情....起床, 上班, 工作, 下班, 睡觉......
要想管理这么多矿工的这么多事情可不简单(好麻烦啊...挨个调用的时候开发者也有可能会忘掉某个人, 或者忘掉某一个方法).,
再举个栗子, 比如操作数据库也一样, 要加载驱动, 建立连接, 操作数据库, 关闭连接. 这么多步骤忘掉一个都会是个问题.
MineWorker抽象类
这里是矿场中工人的统一抽象定义.
public abstract class MineWorker { protected void goToSleep() { System.out.printf("%s 睡觉.\n", name()); } protected void wakeUp() { System.out.printf("%s 早上醒过来.\n", name()); } protected void goHome() { System.out.printf("%s 回家.\n", name()); } protected void goToMine() { System.out.printf("%s 去矿场.\n", name()); } protected abstract void work(); protected abstract String name(); public static enum Action { GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK } public void action(Action... actions) { for (Action action : actions) { switch (action) { case GO_TO_SLEEP: goToSleep(); break; case WAKE_UP: wakeUp(); break; case GO_HOME: goHome(); break; case GO_TO_MINE: goToMine(); break; case WORK: work(); break; default: System.out.println("Undefined action"); break; } } } }
CartOperator类
推车工人.
public class CartOperator extends MineWorker { @Override public void work() { System.out.printf("%s 运输矿石 \n", name()); } @Override public String name() { return "推车工人"; } }
GoldDigger类
挖金矿工人
public class GoldDigger extends MineWorker { @Override public void work() { System.out.printf("%s 挖金矿 .\n", name()); } @Override public String name() { return "挖矿金工人"; } }
TunnelDigger类
挖隧道工人.
public class TunnelDigger extends MineWorker { @Override public void work() { System.out.printf("%s 挖隧道.\n", name()); } @Override public String name() { return "挖隧道工人"; } }
MineFacade类
本系统的门面, 用于对外提供一个简单的接口.
import java.util.ArrayList; import java.util.Collection; import java.util.List; public class MineFacade { private final List<MineWorker> mineWorkers; public MineFacade() { mineWorkers = new ArrayList<>(); mineWorkers.add(new GoldDigger()); mineWorkers.add(new CartOperator()); mineWorkers.add(new TunnelDigger()); } public void startNewDay() { makeActions(mineWorkers, MineWorker.Action.WAKE_UP, MineWorker.Action.GO_TO_MINE); } public void digOutGold() { makeActions(mineWorkers, MineWorker.Action.WORK); } public void endDay() { makeActions(mineWorkers, MineWorker.Action.GO_HOME, MineWorker.Action.GO_TO_SLEEP); } private static void makeActions(Collection<MineWorker> mineWorkers, MineWorker.Action... actions) { for (MineWorker mineWorker : mineWorkers) { mineWorker.action(actions); } } }
Main
在这运行
public class Main { public static void main(String[] args) { // 实例化一个门面, 这是矿场对外提供的一个简单的接口 MineFacade mineFacade = new MineFacade(); // 开始新的一天 mineFacade.startNewDay(); // 大家起来干活 mineFacade.digOutGold(); // 一天结束啦 mineFacade.endDay(); } }
运行结果如下:
---------------------------------------------------------
学如不及,犹恐失之
学如不及,犹恐失之