Python 實現設計模式之工廠模式

語言: CN / TW / HK

highlight: an-old-hope theme: devui-blue


持續創作,加速成長!這是我參與「掘金日新計劃 · 6 月更文挑戰」的第 10 天,點擊查看活動詳情

引言

設計模式是可重複使用的編程方案,已被用於各種現實世界的環境中,並被證明能產生預期的結果。在本文中,我們將學習最常見的設計模式之一:工廠模式

正如我們稍後將看到的,這種模式使我們更容易跟蹤程序中創建的對象,從而將創建對象的代碼與使用對象的代碼分開。我們將研究工廠設計模式的兩種形式:工廠方法抽象方法

設計模式在程序員之間共享,並隨着時間的推移不斷被改進。 這個話題的流行要歸功於 Erich Gamma, Richard Helm, Ralph Johnson, 和 John Vlissides 寫的《設計模式:可複用面向對象軟件的基礎》,根據他們的名字又把書稱為 Gang of Four,GOF。

什麼是設計模式

一般來説,設計模式幫助程序員創建一個常用的實現模式,特別是在面向對象編程(OOP)中。從設計模式的角度看應用程序的好處 從設計模式的角度看應用程序有很多好處。首先,它縮小了建立一個特定的應用程序的最有效的方法和必要的步驟。其次,你可以參考同一設計模式的現有例子來改進你的應用。

總的來説,設計模式是軟件工程中非常有用的準則。

在 OOP 中使用的設計模式有幾類,這取決於它們解決的問題的類型和/或它們幫助我們建立的解決方案的類型。在他們的書中,提出了23種設計模式,分為三類:創造模式結構模式行為模式

什麼是工廠模式

工廠模式屬於創造模式的一種。它提供了創建對象的最佳方法之一。在工廠模式中,對象的創建不向客户端公開邏輯,並使用通用接口引用新創建的對象。

工廠模式在 Python 中使用工廠方法實現的。當用户調用一個方法時,我們傳入一個字符串,返回值作為一個新對象是通過工廠方法實現的。工廠方法中使用的對象類型由通過方法傳遞的字符串確定。

在下面的示例中,每個方法都包含對象作為參數,通過工廠方法實現。

如何實現工廠模式

```python class Button(object): html = "" def get_html(self): return self.html

class Image(Button): html = ""

class Input(Button): html = ""

class Flash(Button): html = ""

class ButtonFactory(): def create_button(self, typ): targetclass = typ.capitalize() return globals()targetclass

button_obj = ButtonFactory() button = ['image', 'input', 'flash'] for b in button: print(button_obj.create_button(b).get_html()) ```

Button 類有助於創建 html 標記和關聯的 html 頁面。客户端將無法訪問代碼的邏輯,輸出代表 html 頁面的創建。

運行結果:

shell $ python factory.py <img></img> <input></input> <obj></obj>

使用 class 關鍵字設計一個類工廠,無非是創建一個持有一個類的函數。讓我們看看下面的代碼:

```python def apple_function(): """Return an Apple class, built using the class keyword""" class Apple(object): def init(self, color): self.color = color

    def getColor(self):
        return self.color
return Apple

invoking class factory function

Apple = apple_function() appleObj = Apple('red') print(appleObj.getColor()) ```

使用類型,我們可以動態地創建類。但是這樣做會把函數和類一起留在命名空間中。讓我們看看這段代碼,以便更好地理解它:

```python def init(self, color): self.color = color

def getColor(self): return self.color

Apple = type('Apple', (object,), { 'init': init, 'getColor': getColor, })

appleRed = Apple(color='red') print(appleRed.getColor()) ```

上面的代碼顯示瞭如何動態地創建類。但問題是,initgetColor 等函數會使命名空間變得雜亂無章,而且我們也無法重複使用這些功能。而通過使用類工廠,你可以最大限度地減少雜亂,並在需要時可以重用這些功能。讓我們看一下下面的代碼。

```python def create_apple_class(): def init(self, color): self.color = color

def getColor(self):
    return self.color

return type('Apple', (object,), {
    '__init__': init,
    'getColor': getColor,
})

Apple = create_apple_class() appleObj = Apple('red') print(appleObj.getColor()) ```

參考鏈接:

  • http://realpython.com/factory-method-python/
  • http://www.geeksforgeeks.org/class-factories-a-powerful-pattern-in-python/