天天看點

【設計模式】建立型模式:工廠模式

文章目錄

  • ​​【設計模式】建立型模式:工廠模式​​
  • ​​基礎類​​
  • ​​工廠類​​
  • ​​測試類​​

【設計模式】建立型模式:工廠模式

定義一個建立對象的接口,讓其子類自己決定執行個體化哪一個工廠類,工廠模式使其建立過程延遲到子類進行

【設計模式】建立型模式:工廠模式

簡要分析,通過一個 Shape 類,有三個實作的子類,然後針對 Shape 建立一個工廠,實際上使用的時候,直接使用工廠即可,也就是工廠統一管理

基礎類

package cn.tellsea.designmode;

/**
 * 圓形
 *
 * @author Tellsea
 * @date 2022/9/26
 */
public class Circle implements Shape {

    @Override
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}      
package cn.tellsea.designmode;

/**
 * 正方形
 *
 * @author Tellsea
 * @date 2022/9/26
 */
public class Square implements Shape {

    @Override
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}      
package cn.tellsea.designmode;

/**
 * 長方形
 *
 * @author Tellsea
 * @date 2022/9/26
 */
public class Rectangle implements Shape {

    @Override
    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }
}      

上面的三個類,繼承下面的統一父類

package cn.tellsea.designmode;

/**
 * 形狀
 *
 * @author Tellsea
 * @date 2022/9/26
 */
public interface Shape {

    /**
     * 繪畫
     */
    void draw();
}      

工廠類

package cn.tellsea.designmode;

/**
 * 形狀工廠
 *
 * @author Tellsea
 * @date 2022/9/26
 */
public class ShapeFactory {

    /**
     * 擷取指定類型的對象
     *
     * @param shapeType
     * @return
     */
    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;
    }
}      

測試類

package cn.tellsea.designmode;

/**
 * 工廠模式
 *
 * @author Tellsea
 * @date 2022/9/26
 */
public class FactoryPatternDemo {

    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();

        //擷取 Circle 的對象,并調用它的 draw 方法
        Shape shape1 = shapeFactory.getShape("CIRCLE");

        //調用 Circle 的 draw 方法
        shape1.draw();

        //擷取 Rectangle 的對象,并調用它的 draw 方法
        Shape shape2 = shapeFactory.getShape("RECTANGLE");

        //調用 Rectangle 的 draw 方法
        shape2.draw();

        //擷取 Square 的對象,并調用它的 draw 方法
        Shape shape3 = shapeFactory.getShape("SQUARE");

        //調用 Square 的 draw 方法
        shape3.draw();
    }
}