
- 設計模式教程
- 設計模式 - 首頁
- 設計模式 - 概述
- 設計模式 - 工廠模式
- 抽象工廠模式
- 設計模式 - 單例模式
- 設計模式 - 建造者模式
- 設計模式 - 原型模式
- 設計模式 - 介面卡模式
- 設計模式 - 橋接模式
- 設計模式 - 過濾器模式
- 設計模式 - 組合模式
- 設計模式 - 裝飾器模式
- 設計模式 - 外觀模式
- 設計模式 - 享元模式
- 設計模式 - 代理模式
- 責任鏈模式
- 設計模式 - 命令模式
- 設計模式 - 直譯器模式
- 設計模式 - 迭代器模式
- 設計模式 - 中介者模式
- 設計模式 - 備忘錄模式
- 設計模式 - 觀察者模式
- 設計模式 - 狀態模式
- 設計模式 - 空物件模式
- 設計模式 - 策略模式
- 設計模式 - 模板模式
- 設計模式 - 訪問者模式
- 設計模式 - MVC模式
- 業務代表模式
- 組合實體模式
- 資料訪問物件模式
- 前端控制器模式
- 攔截過濾器模式
- 服務定位器模式
- 傳輸物件模式
- 設計模式資源
- 設計模式 - 問答
- 設計模式 - 快速指南
- 設計模式 - 有用資源
- 設計模式 - 討論
設計模式 - 工廠模式
工廠模式是Java中最常用的設計模式之一。這種設計模式屬於建立型模式,因為它提供了一種建立物件的好方法。
在工廠模式中,我們建立物件而不向客戶端公開建立邏輯,並使用公共介面引用新建立的物件。
實現
我們將建立一個Shape介面和實現Shape介面的具體類。下一步定義一個工廠類ShapeFactory。
我們的演示類FactoryPatternDemo將使用ShapeFactory來獲取Shape物件。它將資訊(CIRCLE / RECTANGLE / SQUARE)傳遞給ShapeFactory以獲取它需要的物件型別。

步驟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 square shape3.draw(); } }
步驟5
驗證輸出。
Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method.
廣告