Design Patterns in Python (again)

 

11/21/2020 Python Taiwan (Telegram 讀書會)

王銘德

 

大綱

  • 物件相依性問題 (Coupling)
  • 物件生成 (Creational Patterns)
    • Simple Factory, Factory Method, Abstract Factory
    • Builder
    • Prototype
    • Singleton
    • Object Pool
  • 物件結構 (Structural Patterns)
    • Composite
    • Flyweight
    • ...
  • 物件行為 (Behavioral Patterns)
    • ​State
    • Iterator
    • ...

背景知識

什麼是 interface (介面), 或是 Python 裡所謂的 abc (Abstract Base Class)

抽象基本類別

繼承 class

實作 interface

類別 (class) 的關係定義只有兩種

class 繼承

class 脊椎動物():
  def 有脊椎(self):
    return True

  def 叫聲(self):
    print("~~ ~~")

class 貓(脊椎動物):
  def 叫聲(self):
    print("喵... 喵...")

class 狗(脊椎動物):
  def 叫聲(self):
    print("旺... 旺...")
小黃 = 狗()

小黃.叫聲() # 旺... 旺...
print(小黃.有脊椎()) #True
阿花 = 貓()

 

阿花.叫聲() # 喵... 喵...

 

print(阿花.有脊椎()) #True

抽象基本類別(abc)

(跟 interface (介面) 類似, 只定義 抽象 methods)

from abc import ABC, abstractmethod

 

class 電話(ABC):

    @abstractmethod

    def 顯示(self):

        pass

 

class 三星(電話):

    def 顯示(self):

        print("這是一支三星手機")

抽象 method, 一定要在 subclass 定義

Coupling (耦合)

就是物件的相依性的程度

(設計時, 盡可能讓相依性降低)

 

參考 dropbox paper 說明

Design Patterns

就是“類別”與物件的設計模式

討論其可能的 "生成方法", 架構, 或是 "其行為模式 (功能)"

 

其目的, 讓你的程式 物件之間 的耦合度 盡量 降低.

方法: 盡量不要直接用 new (Python 產生物件)

盡量用 interface (Python 用 abc)

盡量用 dependency injection (DI)

(把相關物件用參數帶入, 不要在肚子裡生成物件)

Design Patterns 程式 範例

Simple Factory (簡易工廠模式)

Singleton (單例模式)

State (狀態模式)

Prototype (雛形模式)

Iterator (迭代器模式)

Flyweight (輕盈模式) <-- new

Mediator (仲裁人模式)

MVC Pattern (Django?, Flask?)

Template (模板模式)

FactoryMethod (工廠方法模式)

Builder (建造者模式)

Composite (合成模式)

Object Pool (物件池模式)

Decorator (裝飾模式) <-- new

Observer (監看者模式) (進階RxPy)

* 以上皆連結到 repl.it (fork 成你自己的程式, 來練習)

* 一句老話, ”你沒有自己練習, 無法體會出其中的奧妙和好處“

Good references

Q & A

Design Patterns in Python

By Ming-der Wang

Design Patterns in Python

  • 971