# 前言 這次要來寫設計模式系列 但不會以教學為主,而是以自己學習的結果為主 會簡短的提到每個模式的定義 接著以`Python`作改寫 親自改寫過應該會理解的透徹一點 ## 簡易工廠模式 / 靜態工廠模式 由一個工廠類別負責根據不同的條件返回不同類別的物件。 缺點是違反開閉原則(OCP,Open/Closed Principle),每次增加新類別都需要修改工廠的邏輯。 ```python= class Product(): """產品""" def information(self): pass class MilkTea(Product): """奶茶類別""" def information(self): return "it's milk tea" class BlackTea(Product): """紅茶類別""" def information(self): return "it's black tea" class BubbleTeaStore(): """手搖杯店""" @staticmethod def make_drinks(drink_type: str): # 實務上可以將 drink_type 寫成 Enum 類別,方便維護 if drink_type.lower() == "milk_tea": return MilkTea() if drink_type.lower() == "black_tea": return BlackTea() raise ValueError("Unknown drink type") if __name__ == '__main__': my_drink = BubbleTeaStore.make_drinks("milk_tea") print(my_drink.information()) ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up