外观模式将多个子系统及其之间的复杂关系和调用流程封装到一个统一的接口或类中以对外提供服务。
示例:
(1)定义子系统
public class DashBoard{ private final static Log logger = LogFactory.getLog(this.getClass()); public void startup(){ logger.info("dashboard startup......"); } public void shutdown(){ logger.info("dashboard shutdown......"); } } public class Engine{ private final static Log logger = LogFactory.getLog(this.getClass()); public void startup(){ logger.info("engine startup......"); } public void shutdown(){ logger.info("engine shutdown......"); } } public class SelfCheck{ private final static Log logger = LogFactory.getLog(this.getClass()); public void startupCheck(){ logger.info("startup check"); } public void shutdown(){ logger.info("shutdown check finished"); } }
(2)定义门面类
public class Starter{ private final static Log logger = LogFactory.getLog(this.getClass()); private DashBoard dashBoard; private Engine engine; private SelfCheck selfCheck; public Starter(){ this.dashBoard = new DashBoard(); this.engine = new Engine(); this.selfCheck = new SelfCheck(); } public void startup(){ logger.info("car begin startup"); engine.startup(); dashBoard.startup(); selfCheck.startupCheck(); logger.info("car startup finished"); } public void shutdown(){ logger.info("car begin shutdown"); engine.shutdown(); dashBoard.shutdown(); selfCheck.shutdown(); logger.info("car shutdown finished"); } }
(3)使用外观模式
public static void main(String[] args){ Starter starter = new Starter(); starter.startup(); starter.shutdown(); }