2024-06-10|閱讀時間 ‧ 約 27 分鐘

設計模式與程式架構(五)

    ※ 工廠模式

    定義:

    工廠模式是一種實現了「工廠」概念的物件導向設計模式。它提供一個通用的工廠介面,將創建instance(實例)的程式碼交由子類別各自實現並根據需求去動態地生成相應的物件。這種模式將物件的創建邏輯與使用邏輯分開,使程式碼更容易維護和擴展。

    特點:

    具有高度標準化和同質性的特點,僅存在一些很小的差異。

    優點:

    • 使用者無需了解工廠內部的具體實作過程,只需給出關鍵字即可獲得所需的產品實例。這提高了使用的便利性。
    • 產品擁有高度同質性,各個實例的功能非常一致,只有微小差異。這確保了產品的穩定性和可靠性。
    • 隱藏了工廠內部的複雜性,讓使用者能專注於自己的需求,而不必過多關注產品的內部實現。有助於提升使用體驗。

    使用場合:

    • 當一系列物件具有相似的性質,只有少部分差異時,工廠模式能夠很好地管理這種情況。

    舉例來說,使用工廠模式來管理電子商務網站裡面的多種類型的產品,例如電腦、手機、平板等品項就不必關心每種產品的具體細節。同時,工廠模式巧妙地運用了多型的概念,讓客戶端代碼可以透過通用的介面和方法來操作不同類型的產品,這增加了代碼的靈活性和可讀性。

    ※ 工廠模式範例

    共同條件:

    //共同有輪子和車子的類型
    interface Car {
    wheelNumber: number
    carType: string

    getType(): string
    getName(): string
    }
    //輪子和車子的類型內容不一樣
    class BMW implements Car {
    wheelNumber: number = 4
    carType: string = "car"

    getType = () => this.carType
    getName = () => this.constructor.name
    }
    class Mitsubishi_Fuso implements Car {
    wheelNumber: number = 4
    carType: string = "truck"

    getType = () => this.carType
    getName = () => this.constructor.name
    }
    class RAV4 implements Car {
    wheelNumber: number = 4
    carType: string = "rv"

    getType = () => this.carType
    getName = () => this.constructor.name
    }

    ※ 簡單工廠模式寫法:

    //將製造車子的程式碼包裝在工廠模式中
    class SimpleFactory {
    static getCar = (type: string) => {
    switch (type) {
    case "BMW": return new BMW()
    case "mitsubishi": return new Mitsubishi_Fuso()
    case "RAV": return new RAV4()
    }
    }
    }
    //簡單工廠模式
    const car1 = SimpleFactory.getCar('BMW')
    const car2 = SimpleFactory.getCar('mitsubishi')
    const car3 = SimpleFactory.getCar('RAV')

    console.log(car1?.getName(), "-->", car1?.getType())
    console.log(car2?.getName(), "-->", car2?.getType())
    console.log(car3?.getName(), "-->", car3?.getType())
    // ​BMW --> car
    // MitsubishiFuso --> truck
    // RAV4 --> rv

    ※ 抽象工廠模式寫法:

    //將改成工廠改成專一化,讓每個工廠都專門生產自己的車子。
    class Factory {
    //擁有 getCar的屬性
    static getCar() {

    }
    }
    //好處是未來需要什麼樣的車子,就去建立它專屬的工廠
    class BMWFactory implements Factory {
    static getCar() {
    return new BMW()
    }
    }

    class MitsubishiFusoFactory implements Factory {
    static getCar() {
    return new MitsubishiFuso()
    }
    }

    class RAV4Factory implements Factory {
    static getCar() {
    return new RAV4()
    }
    }

    const car1 = BMWFactory.getCar()
    const car2 = MitsubishiFusoFactory.getCar()
    const car3 = RAV4Factory.getCar()

    console.log(car1.getName(), "-->", car1.getType())
    console.log(car2.getName(), "-->", car2.getType())
    console.log(car3.getName(), "-->", car3.getType())
    // ​BMW --> car
    // MitsubishiFuso --> truck
    // RAV4 --> rv




    分享至
    成為作者繼續創作的動力吧!
    © 2024 vocus All rights reserved.