设计模式之——外观or门面模式

1.概念

  定义一个高层的统一的外观接口类,该接口用于客户端调用,和一个实现类用来包装子系统中多个类,客户端可以通过客户端完成对子系统的方法调用。

2.适用场景

  2.1 代码移植,降低了现有系统的复杂度和系统中的编译依赖性。

  2.2 多步骤的操作,简化了接口,降低了与子系统的耦合度。

缺点:违背开闭原则,如果引入子系统,则可能需要修改外观类和客户操作。

3.实现

 为了设计方便,子系统一和二相似,如下显示名字和年龄。

 1 package FaceCode;
 2 
 3 public interface SunOne {
 4     String showName();
 5     int showAge();
 6 }
 7 
 8 
 9 
10 package FaceCode;
11 
12 public class SunOneImpl implements SunOne {
13     public SunOneImpl() {
14     }
15 
16     public String showName() {
17         return "sun one";
18     }
19 
20     public int showAge() {
21         return 10;
22     }
23 }

 

外观类:

 1 package FaceCode;
 2 
 3 public interface FartherFace {
 4     String showSunOneOfName();
 5     String showSunTwoOfName();
 6     int showSunOneOfAge();
 7     int showSunTwoOfAge();
 8 }
 9 
10 
11 package FaceCode;
12 
13 public class FartherFaceImpl implements FartherFace {
14     public FartherFaceImpl() {
15     }
16 
17     public String showSunOneOfName() {
18         return (new SunOneImpl()).showName();
19     }
20 
21     public String showSunTwoOfName() {
22         return (new SunTwoImpl()).showName();
23     }
24 
25     public int showSunOneOfAge() {
26         return (new SunOneImpl()).showAge();
27     }
28 
29     public int showSunTwoOfAge() {
30         return (new SunTwoImpl()).showAge();
31     }
32 }

 

4.外观模式和适配器模式区别

  外观模式:多个子系统包装成统一成一个类接口,提供对外调用。

  适配器模式:一个接口转换成不同接口。

posted @ 2018-12-05 12:38  sun-sailing  阅读(296)  评论(0编辑  收藏  举报