外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端能够访问系统的接口。这种类型的设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。java
这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。设计模式
意图
为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。安全
主要解决
下降访问复杂系统的内部子系统时的复杂度,简化客户端与之的接口。ide
如何解决
客户端不与系统耦合,外观类与系统耦合。设计
关键代码
在客户端和复杂系统之间再加一层,这一层将调用顺序、依赖关系等处理好。code
缺点
不符合开闭原则,若是要改东西很麻烦,继承重写都不合适。blog
咱们将建立一个Shape
接口和实现了Shape
接口的实体类。下一步是定义一个外观类ShapeMaker
。继承
ShapeMaker
类使用实体类来表明用户对这些类的调用。FacadePatternDemo
,咱们的演示类使用ShapeMaker
类来显示结果。接口
Shape.java
public interface Shape { void draw(); }
Rectangle.javaci
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Rectangle::draw()"); } }
Square.java
public class Square implements Shape { @Override public void draw() { System.out.println("Square::draw()"); } }
Circle.java
public class Circle implements Shape { @Override public void draw() { System.out.println("Circle::draw()"); } }
ShapeMaker.java
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 static void main(String[] args) { ShapeMaker shapeMaker = new ShapeMaker(); shapeMaker.drawCircle(); shapeMaker.drawRectangle(); shapeMaker.drawSquare(); } }
Circle::draw() Rectangle::draw() Square::draw()