1. 程式人生 > >設計模式之外觀模式——Java語言描述

設計模式之外觀模式——Java語言描述

外觀模式隱藏系統的複雜性,並向客戶端提供了一個客戶端可以訪問系統的介面。它想現有的系統添加了一個介面,以隱藏系統的複雜性

介紹

意圖

為子系統中的一組介面提供了一個一致的介面,外觀模式定義了一個高層介面,這個介面使得這一子系統更加容易使用

應用例項

  1. 電腦只要按下開機鍵,就會自動執行開機的程式
  2. Java的三層開發模式

優點

  1. 減少系統相互依賴
  2. 提高靈活性
  3. 提高安全性

缺點

不符合開閉原則,如果需要修改東西很麻煩,繼承重寫都不合適。

實現

我們將建立一個 Shape 介面和實現了 Shape 介面的實體類。下一步是定義一個外觀類 ShapeMaker。

ShapeMaker 類使用實體類來代表使用者對這些類的呼叫。FacadePatternDemo,我們的演示類使用 ShapeMaker 類來顯示結果。

建立Shape介面

public interface Shape {
   void draw();
}

建立實現介面的實體類

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

建立一個外觀類。

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

使用該外觀類畫出各種型別的形狀。

FacadePatternDemo.java
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()