公号:码农充电站pro
主页:https://codeshellme.github.iohtml
今天来介绍外观模式(Facade Design Pattern)。java
外观模式又叫门面模式,它提供了一个统一的(高层)接口,用来访问子系统中的一群接口,使得子系统更容易使用。git
外观模式的类图以下:github
Facede 简化了原来的很是复杂的子系统,使得子系统更易使用,Client 只需依赖 Facede 便可。算法
虽然有了 Facede ,但 Facede 并影响原来的子系统,也就是其它客户依然能够使用原有系统。shell
最少知识原则告诉咱们,应该尽可能减小对象之间的交互,只与本身最须要的接口创建关系。this
在设计系统时,不该该让太多的类耦合在一块儿,以避免一小部分的改动,而影响到整个系统的使用。设计
这也就是咱们俗话说的:牵一发而动全身,最少知识原则的就是让咱们避免这种状况的发生。code
外观模式则使用了最少知识原则。htm
下面举一个简单的例子,来体会下外观模式的使用。俗话说:民以食为天。咱们来举一个吃饭的例子。
话说,小明每次吃饭都要通过如下步骤:
可见小明吃一顿饭真的很麻烦。
咱们用代码来模拟上面的过程,首先建立了三个类,分别是关于菜,饭,碗的操做:
class Vegetables { public void bugVegetables() { System.out.println("buying vegetables."); } public void washVegetables() { System.out.println("washing vegetables."); } public void fryVegetables() { System.out.println("frying vegetables."); } public void toBowl() { System.out.println("putting the vegetables into the bowl."); } } class Rice { public void fryRice() { System.out.println("frying rice."); } public void toBowl() { System.out.println("putting the rice into the bowl."); } } class Bowl { private Vegetables vegetables; private Rice rice; public Bowl(Vegetables vegetables, Rice rice) { this.vegetables = vegetables; this.rice = rice; } // 盛好饭菜 public void prepare() { vegetables.toBowl(); rice.toBowl(); } public void washBowl() { System.out.println("washing bowl."); } }
小明每次吃饭都须要与上面三个类作交互,并且须要不少步骤,以下:
Vegetables v = new Vegetables(); v.bugVegetables(); v.washVegetables(); v.fryVegetables(); Rice r = new Rice(); r.fryRice(); Bowl b = new Bowl(v, r); b.prepare(); System.out.println("xiao ming is having a meal."); b.washBowl();
后来,小明请了一位保姆,来帮他作饭洗碗等。因此咱们建立了 Nanny
类:
class Nanny { private Vegetables v; private Rice r; private Bowl b; public Nanny() { v = new Vegetables(); r = new Rice(); b = new Bowl(v, r); } public void prepareMeal() { v.bugVegetables(); v.washVegetables(); v.fryVegetables(); r.fryRice(); b.prepare(); } public void cleanUp() { b.washBowl(); } }
这样,小明再吃饭的时候就只须要跟保姆说一声,保姆就帮他作好了全部的事情:
Nanny n = new Nanny(); n.prepareMeal(); System.out.println("xiao ming is having a meal."); n.cleanUp();
这样大大简化了小明吃饭的步骤,也节约了不少时间。
我将完整的代码放在了这里,供你们参考。
外观模式主要用于简化系统的复杂度,为客户提供更易使用的接口,减小客户对复杂系统的依赖。
从外观模式中咱们也能看到最少知识原则的运用。
(本节完。)
推荐阅读:
欢迎关注做者公众号,获取更多技术干货。