Neil 啃設計模式(0x02)工廠模式

工廠模式(Factory Pattern)

定義

Define an interface for creating an object,but let subclasses decide which class to instantiate.Factory Method lets a class defer instantiation to subclasses.(定義一個用於建立對象的接口,讓子類決定實例化哪個類。工廠方法使一個類的實例化延遲到其子類。)
對於python這種運行時判斷類型的腳本語言來講,就是一個簡單工廠方法,經過工廠方法屏蔽對應的子類的建立。java

UML 示例

@startuml
class NvWa
note left:女媧
abstract class AbstractHumanFactroy{
    Human createHuman(Class c)
}
note left: 抽象八卦爐
interface Human{
    +void getColor()
    +void talk()
}
note left:人類

NvWa -->AbstractHumanFactroy
NvWa -->Human
AbstractHumanFactroy ..> Human

class HumanFactory
class BlackHuman
note bottom: 黑色人種
class YellowHuman
note bottom: 黃色人種
class WhiteHuman
note bottom: 白色人種
AbstractHumanFactroy <|--HumanFactory

Human<|..BlackHuman
Human<|..YellowHuman
Human<|..WhiteHuman

@enduml

image.png

代碼實現

圖示中表示的 uml 類間的關係,因爲 python 中沒有接口概念,而 uml 中定義了做爲全部 human 實現的接口,在 python 的表示的話就是各個具體的類定義。
靜態語言中有接口,抽象類,而 python 中類型是在運行時檢查的,因此有些區別,看起來也相對簡單。
好比:代碼中關於工廠類,其實在 java 中也不過是一個 factory 工廠定義一個靜態方法,與此處直接用一個工廠方法表示同樣。python

class BlackHuman:

    def __init__(self):
        return

    def talk(self):
        print("I'm blcak human")

    def getColor(self):
        print("Black")


class WhiteHuman:

    def __init__(self):
        return

    def talk(self):
        print("I'm white human")

    def getColor(self):
        print("White")


class YellowHuman:

    def __init__(self):
        return

    def talk(self):
        print("I'm yellow human")

    def getColor(self):
        print("Yellow")


def create_human(selector):
    if selector == 'black':
        return BlackHuman()
    if selector == 'white':
        return WhiteHuman()
    if selector == 'yellow':
        return YellowHuman()

    return ValueError("selector is wrong")


if __name__ == "__main__":
    #  NvWa造人
    blackhuman = create_human('black')
    whitehuman = create_human('white')
    yellowhuman = create_human('yellow')

    blackhuman.getColor()
    whitehuman.getColor()
    yellowhuman.getColor()

知識點

  • 簡單工廠使用的方法相對簡單,但須要注意的是應用場景,我的理解凡是想要封閉建立某個具體對象時,均可使用簡單工廠。好比鏈接數據庫時,鏈接的不一樣的數據庫,返回一個對應數據庫的對象,此時經過工廠方法屏蔽掉具體建立細節;只是經過傳入的參數類型來判斷。
  • 再好比:根據不一樣的文件後綴,建立不一樣文件類型的對象,解析對應的文件類型。數據庫

    參考《精通 python 設計模式》第一章工廠模式之工廠方法
    參考《設計模式之禪》

下集預告:抽象工廠模式

相關文章
相關標籤/搜索