运行GoF 定义:为系统中一系列的接口提供一个统一的接口。外观模式定义了一个更高层的接口,使得子系统更容易使用。( Provide a unified interface to a set of interfaces in a system. Facade defines a higher-level interface that makes the subsystem easier to use.)
进一步解释:外观模式是一种很直白的设计思路,就是用一个类包含多个类对象,以实现统一的调用接口。例如,我们设计一个图形界面程序,写了一堆在桌面上绘制不同图形的类(Line, Ract, Circle等)。然后我们用一个更高层的类(DrawShape)包装这些类,这样用户只需要跟DrawShape打交道即可,简化了程序员需要使用到的接口。反过来,如果我们要设计这样一个图形程序,自上而下的设计方法告诉我们,首先应该写一个总体的接口,然后再考虑细节部分的实现。这就是外观模式。
使用代码来呈现上述的例子:
import java.util.Random;
/**
* Facade patterns
*/
// 外观类,提供了三种不同形状的上层接口
class DrawShapeFacade {
private Line line;
private Circle circle;
private Rect rect;
public DrawShapeFacade() {
this.line = new Line();
this.circle = new Circle();
this.rect = new Rect();
}
public void setLinePara(float length) {
line.setLength(length);
}
public void setCirclePara(float radius) {
circle.setRadius(radius);
}
public void setRectPara(float len, float wid) {
rect.setLength(len);
rect.setWidth(wid);
}
public void drawAll() {
line.draw();
circle.draw();
rect.draw();
}
}
class Line {
private float length;
public void setLength(float length) {
this.length = length;
}
public void draw() {
System.out.printf("Draw a line, with length %.2f \n", length);
}
}
class Circle {
private float radius;
public void setRadius(float radius) {
this.radius = radius;
}
public void draw() {
System.out.printf("Draw a circle with radius %.2f\n", radius);
}
}
class Rect {
private float length;
private float width;
public void setLength(float length) {
this.length = length;
}
public void setWidth(float width) {
this.width = width;
}
public void draw() {
System.out.printf("Draw a rectangular, l=%.2f, w=%.2f\n", length, width);
}
}
public class Main {
public static void main(String[] args) {
DrawShapeFacade shapeFacade = new DrawShapeFacade();
shapeFacade.setCirclePara(10);
shapeFacade.setLinePara(2.13F);
shapeFacade.setRectPara(3.2F, 4.0F);
shapeFacade.drawAll();
}
}
运行结果:
程序结构: