Java 设计模式10——外观模式

模式定义

外观模式,结构型模式,隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。通过这个接口来向客户端隐藏系统内部的复杂性。简单来说,就是通过一个类来讲复杂系统的访问简化,使得客户端只用通过这个类来访问(通常是方法调用)系统,而无需关系系统该功能的具体实现。

代码示例

现在有一个绘图系统,可以绘制圆形、长方形、三角形,现在有一个只认识几个字的小白,要让他使用系统,我们就要创建一个小白页面,告诉他按那个可以画圆形,按哪个可以画长方形,这样这个小白在使用系统时,只需要简单的点击界面上的几个按钮就可以使用绘图系统,根本不需要掌握系统到底是则呢实现的。我的提供的这个小白页面就是系统功能的抽象外观。具体实现如下:

  1. 建立绘图系统,提供圆形、长方形、三角形的绘制方法;
  2. 建立一个小白界面,让小白用户直接使用;
  3. 小白通过小白界面调用系统。

首先建立绘图系统

1
2
3
public interface Shape {
void draw();
}
1
2
3
4
5
6
7
public class Circle implements Shape {

@Override
public void draw() {
System.out.println("Circle::draw()");
}
}
1
2
3
4
5
6
7
public class Rectangle implements Shape {

@Override
public void draw() {
System.out.println("Rectangle::draw()");
}
}
1
2
3
4
5
6
7
public class Triangle implements Shape {

@Override
public void draw() {
System.out.println("Triangle::draw()");
}
}

然后,建立小白页面(绘图系统的使用终端)

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 ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape triangle;

public ShapeMaker() {
circle = new Circle();
rectangle = new Rectangle();
triangle = new Triangle();
}

void draw() {
drawCircle();
drawRectangle();
drawTriangle();
}

public void drawCircle(){
circle.draw();
}
public void drawRectangle(){
rectangle.draw();
}
public void drawTriangle(){
triangle.draw();
}
}

小白用户调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class FacadeClient {

public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();

shapeMaker.draw();

shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawTriangle();
}
}
// 输出结果
Circle::draw()
Rectangle::draw()
Triangle::draw()
Circle::draw()
Rectangle::draw()
Triangle::draw()

模式总结

外观模式,其实就是让客户端与系统不耦合,让外观类(上例中的ShapeMaker)与系统耦合。

优缺点

  • 优点
    • 使用简单,用户只需要通过终端调用操作即可;
    • 客户端与具体的系统实现解耦了,具体系统只与小白界面(外观)耦合
    • 灵活,需要增加新的图形绘制,只需要系统增加新图形绘制能力,然后小白界面增加功能调用即可;
    • 安全,用户无法直接接触到系统。
  • 缺点
    • 违反了开闭原则,要扩展功能,就必须修改系统代码,必修修改小白界面的外观。

使用场景

单系统存在多个环节,多个功能,能独立调用时,为了规避使用的复杂性,可以使用外观模式,让使用者通过一个提供了系统功能访问能了的小白界面(外观)来使用系统,既安全又易用。