外观模式
外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。向现有的系统添加一个接口,来隐藏系统内部。客户端只需要调用接口、而无需在意实现细节
UML:

外观模式的主要角色:
- Facade:外观角色
- Client:外观接口调用者
- 子系统:各个功能模块,完成Facade指派的任务,是实际实现功能的角色
Cast:
去餐厅吃饭的时候我们只需要叫服务员点餐,然后等着上菜吃饭,最后结账离开就可以了
子系统:Cook类、Waiter类
1 // 厨师 2 public class Cook { 3 private static Cook cook = new Cook(); 4 5 public static Cook getInstance() { 6 return cook; 7 } 8 9 public void cooking() { 10 System.out.println("厨师烧菜"); 11 } 12 13 public void notifyWaiter() { 14 System.out.println("厨师通知服务员"); 15 } 16 } 17 18 // 服务员 19 public class Waiter { 20 private static Waiter waiter = new Waiter(); 21 22 public static Waiter getInstance() { 23 return waiter; 24 } 25 26 public void order() { 27 System.out.println("服务员点餐"); 28 } 29 30 public void notifyCook() { 31 System.out.println("服务员将点菜单拿给厨师"); 32 } 33 34 public void serve() { 35 System.out.println("服务员上菜"); 36 } 37 38 public void clearUp() { 39 System.out.println("服务员收拾餐桌"); 40 } 41 42 public void Washing() { 43 System.out.println("服务员清洗餐具"); 44 } 45 46 public void checkOut() { 47 System.out.println("服务员结账"); 48 } 49 }
Client:
1 public static void main(String[] args) { 2 3 Restaurant r = new Restaurant(); 4 r.order(); 5 System.out.println("--------\n吃饭中\n--------"); 6 r.checkOut(); 7 }
Facade:Restaurant类
1 public class Restaurant { 2 private Cook cook = Cook.getInstance(); 3 private Waiter waiter = Waiter.getInstance(); 4 5 public void order() { 6 waiter.order(); 7 waiter.notifyCook(); 8 cook.cooking(); 9 cook.notifyWaiter(); 10 waiter.serve(); 11 } 12 13 public void checkOut() { 14 waiter.checkOut(); 15 waiter.clearUp(); 16 waiter.Washing(); 17 } 18 }
总结:
在需求分析的时候,要有意识的将系统分层设计,层与层之间建立外观模式,如DAO、ServiceImpl、Service的关系
在旧系统难以维护但是又有非常重要的功能时,可以为其定制一个外观类,以便新旧系统交互

浙公网安备 33010602011771号