首頁  >  文章  >  Java  >  Java工廠設計模式課程詳解

Java工廠設計模式課程詳解

(*-*)浩
(*-*)浩原創
2019-11-26 14:30:461948瀏覽

Java工廠設計模式課程詳解

工廠模式是Java中最常用的設計模式之一。這種類型的設計模式屬於建立模式,因為此模式提供了創建物件的最佳方法之一。

# 在工廠模式中,我們沒有建立邏輯暴露給客戶端建立對象,並使用一個通用的介面來引用新建立的對象。      (建議學習:java課程

#實作方法

##我們將建立一個Shape介面和實作Shape介面的特定類別。一個工廠類別ShapeFactory會在下一步定義。


    FactoryPatternDemo這是一個示範類,將使用ShapeFactory來取得一個Shape物件。它會將資訊(CIRCLE/RECTANGLE/SQUARE)傳遞給ShapeFactory以取得所需的物件類型。

實作工廠模式的結構如下圖所示-

Java工廠設計模式課程詳解

#第1步

# 建立一個介面-

Shape.java
public interface Shape {
   void draw();
}

   

第2步驟

    建立實現相同介面的特定類別。如下所示幾個類別 -

Rectangle.java
public class Rectangle implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
Square.java
public class Square implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}
Circle.java
public class Circle implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

   

第3步驟

建立工廠根據給定的資訊產生特定類別的物件。

ShapeFactory.java
public class ShapeFactory {
   //use getShape method to get object of type shape 
   public Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }        
      if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();
      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }
      return null;
   }
}

   

第4步

# 使用工廠透過傳遞類型等資訊來取得特定類別的物件。

FactoryPatternDemo.java
public class FactoryPatternDemo {
   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();
      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");
      //call draw method of Circle
      shape1.draw();
      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");
      //call draw method of Rectangle
      shape2.draw();
      //get an object of Square and call its draw method.
      Shape shape3 = shapeFactory.getShape("SQUARE");
      //call draw method of circle
      shape3.draw();
   }
}

   

第5步驟

# 驗證輸出結果如下-

Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.

以上是Java工廠設計模式課程詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn