目录

设计模式 - 立面图案( Facade Pattern)

Facade模式隐藏了系统的复杂性,并为客户端提供了一个接口,客户端可以使用该接口访问系统。 这种类型的设计模式属于结构模式,因为这种模式为现有系统添加了一个接口以隐藏其复杂性。

此模式涉及单个类,它提供客户端所需的简化方法,并委托对现有系统类的方法的调用。

实现 (Implementation)

我们将创建一个Shape接口和实现Shape接口的具体类。 Facade类ShapeMaker被定义为下一步。

ShapeMaker类使用具体类将用户调用委托给这些类。 我们的演示类ShapeMaker将使用ShapeMaker类来显示结果。

门面图案UML图

Step 1

创建一个界面。

Shape.java

public interface Shape {
   void draw();
}

Step 2

创建实现相同接口的具体类。

Rectangle.java

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()");
   }
}

Step 3

创建一个外观类。

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();
   }
}

Step 4

使用立面绘制各种类型的形状。

FacadePatternDemo.java

public class FacadePatternDemo {
   public static void main(String[] args) {
      ShapeMaker shapeMaker = new ShapeMaker();
      shapeMaker.drawCircle();
      shapeMaker.drawRectangle();
      shapeMaker.drawSquare();		
   }
}

Step 5

验证输出。

Circle::draw()
Rectangle::draw()
Square::draw()
↑回到顶部↑
WIKI教程 @2018