设计模式源码git地址:design-pattern-src: 设计模式源码 (gitee.com)

  1. 通用类图
  2. 场景举例
  3. 优点
  4. 缺点
  5. 注意
  6. 总结

通用类图

img

把功能统一到一块,形成一个总控,就类似于家里电闸的总开关,可以控制所有的电器

就拿我们公司举例,如果我平时遇到某个系统的问题,比如财务的问题找财务系统负责人,人力的找人力负责人,我还得知道他们是谁,我也没必要记住他们,那么一个角色出现了,充当了中间人的作用,那就是客服,我知道如果出问题了,就去找她,她给我找具体的人,这就是外观模式的一种体现

角色

这样看下来一共有两个角色

外观,相当于客服

子系统,相当于各个部门的负责人

场景举例

拿总控进行举例,如果我按总开关打算控制家中所有的灯,那么代码如下

先看调用端

1
2
3
4
5
6
7
8
9
10
//外观模式,一步齐活
new Facade().open();
new Facade().close();
//传统方式,挨个调用
new BedRoom().open();
new Kitchen().open();
new LivingRoom().open();
new BedRoom().close();
new Kitchen().close();
new LivingRoom().close();

外观类

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Facade {
void open(){
new BedRoom().open();
new Kitchen().open();
new LivingRoom().open();
}

void close(){
new BedRoom().close();
new Kitchen().close();
new LivingRoom().close();
}
}

3个子类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class BedRoom {
void open(){
System.out.println("打开卧室的灯");
}

void close(){
System.out.println("关闭卧室的灯");
}
}
public class Kitchen {
void open(){
System.out.println("打开厨房的灯");
}

void close(){
System.out.println("关闭厨房的灯");
}
}
public class LivingRoom {
void open(){
System.out.println("打开客厅的灯");
}

void close(){
System.out.println("关闭客厅的灯");
}
}

优点

相当于封装了一层,子系统怎么变不影响,提供统一入口,方便调用,降低客户类与子系统的耦合度(可以想作,我只需要找客服,不需要找其他人了,降低与他们的联系,也就是耦合)

缺点

符合迪米特法则(最少知道),但不符合开闭原则(每次子系统添加方法,外观类都得改变)

注意

1、通常只需要一个外观类,因为他本来就是总开关的角色,你在写个类继承他,给他增加方法,那就违背了它本来的意义

总结

网上看了几个有jdbcutils的,tomcat的一些源码,但我觉得都有点牵强,不得不说这个模式技术点并不多,只是提供了一个统一封装的思想