1、基本介绍
- 外观模式(Facade Pattern,也称为“门面模式”)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。这种类型的设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。
- 这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。
- 为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
- 降低访问复杂系统的内部子系统时的复杂度,简化客户端之间的接口。
2、具体案例
我们以画画为例,画一幅画可能会画出各种形状,如果不用外观模式,我们要自己一个个画出这些形状。用了外观模式,就像用了某种画图工具,只需要从工具栏拖出某种形状即可。
创建抽象类
public interface Shape {void draw();}
创建具体实现
public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Circle draw");}}public class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("Rectangle draw");}}public class Square implements Shape {@Overridepublic void draw() {System.out.println("Square draw");}}
创建外观类 ```java public class ShapeMaker {
private Rectangle rectangle; private Square square; private Circle circle;
public ShapeMaker() {
circle = new Circle();rectangle = new Rectangle();square = new Square();
}
public void drawCircle() {
circle.draw();
}
public void drawRectangle() {
rectangle.draw();}
public void drawSquare() {
square.draw();} }
- 测试
```java
public class FacadePatternDemo {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
}

