外观模式
2021年10月23日大约 2 分钟约 475 字
1. 概念
外观模式(Facade Pattern)在于隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。
如果客户端要跟许多子系统打交道,那么客户端需要了解各个子系统的接口,比较麻烦。而如果有一个统一的“中介”,让客户端只跟中介打交道,中介再去跟各个子系统打交道,对客户端来说就比较简单,所以Facade就相当于搞了一个中介。
为了给子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
外观模式的优点是减少系统相互依赖、提高灵活性、提高安全性,但缺点是不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。
2. 示例
我们首先创建一个 Shape
接口和实现了 Shape
接口的实体类,然后定义一个外观类 ShapeMaker
,该类使用实体类来代表用户对这些类的调用,最后客户端类 FacadePatternDemo
使用 ShapeMaker
类来显示结果。
创建一个接口
public interface Shape { void draw(); }
创建实现接口的实体类
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Rectangle::draw()"); } }
public class Square implements Shape { @Override public void draw() { System.out.println("Square::draw()"); } }
public class Circle implements Shape { @Override public void draw() { System.out.println("Circle::draw()"); } }
创建一个外观类
public class ShapeMaker { private Shape circle; private Shape rectangle; private Shape square; 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(); } }
使用该外观类画出各种类型的形状
public class FacadePatternDemo { public static void main(String[] args) { ShapeMaker shapeMaker = new ShapeMaker(); shapeMaker.drawCircle(); shapeMaker.drawRectangle(); shapeMaker.drawSquare(); } }
执行程序,输出结果: Circle::draw() Rectangle::draw() Square::draw()