外观模式
定义
外观模式,又称门面模式,它提供了一个统一的接口,用来访问子系统中的一群接口。外观定义了一个高层接口,让子系统更容易使用。
架构示意图:
意图:
提供一个简单接口,让子系统更易于使用。
最少知识原则:
Least Knowledge:只和你的密友交谈。
这个原则希望我们在设计中,不要让太多的类耦合在一起,免得修改系统中一部分,会影响到其他部分。如果许多类之间相互依赖,那么这个系统就会变成一个易碎的系统,它需要花许多成本维护,也会因为太复杂而不容易被其他人了解。
要点:
1. 当需要简化并统一一个很大的接口或者一群复杂的接口时,使用外观。
2. 外观将客户从一个复杂的子系统中解耦。
3. 实现一个外观,需要将子系统组合进外观中,然后将工作委托给子系统执行。
实例
子系统:
Gas :子系统——天然气对象
public class Gas { public void open() { System.out.println("open the gas!"); } public void close() { System.out.println("close the gas!"); } } |
Oil :子系统——油对象
public class Oil { public void put() { System.out.println("put the oil"); } } |
Pot :子系统——锅对象
public class Pot { public void cook() { System.out.println("cook!"); } public void finished() { System.out.println("finished"); } } |
Vegetables :子系统——蔬菜类
public class Vegetables { public void put() { System.out.println("put the vegetalbes!"); } } |
Facade :门面对象
public class Facade { public void cook() { Gas gas = new Gas(); Oil oil = new Oil(); Vegetables vegetables = new Vegetables(); Pot pot = new Pot(); gas.open(); oil.put(); vegetables.put(); pot.cook(); pot.finished(); gas.close(); } } |
Client :客户端
public class Client { public static void main(String args[]) { //1.旧的方法,客户端需要知道很多子系统对象 Client client = new Client(); client.method1(); //2.门面模式,解耦,客户端只需要知道门面对象即可 Facade facade = new Facade(); facade.cook(); } /** * 旧的客户端方法 */ public void method1() { Gas gas = new Gas(); Oil oil = new Oil(); Vegetables vegetables = new Vegetables(); Pot pot = new Pot(); gas.open(); oil.put(); vegetables.put(); pot.cook(); pot.finished(); gas.close(); } } |