# 前言 這個系列的第二篇 改寫的是工廠方法模式(Factory Method Pattern) # 工廠方法模式 定義一個抽象工廠接口,讓具體的子類別決定要創建哪一種物件。 子類別可以自行決定要創建的物件類型。 優點是遵循了開閉原則,添加新類別不需要修改現有的程式碼。 ```python= from abc import ABC, abstractmethod class Weapon(ABC): # 定義抽象物件及其必須實作的抽象方法 @abstractmethod def effective_range(self): ... @abstractmethod def magazine_capacity(self): ... class Rifle(Weapon): # M4 def effective_range(self): return "effective range: 500m" def magazine_capacity(self): return "magazine capacity: 30" class MachineGun(Weapon): # M249 def effective_range(self): return "effective range: 1000m" def magazine_capacity(self): return "magazine capacity: 200" class WeaponFactory(ABC): # 定義抽象工廠接口 @abstractmethod def produce_weapon(self): ... class RifleFactory(WeaponFactory): def produce_weapon(self): return Rifle() class MachineGunFactory(WeaponFactory): def produce_weapon(self): return MachineGun() if __name__ == "__main__": gun_factory = MachineGunFactory() my_weapon = gun_factory.produce_weapon() print(my_weapon.effective_range()) print(my_weapon.magazine_capacity()) ``` # 心得 這邊使用了`ABC`以及`abstractmethod` 用來更好的模擬`C#`或`Java`的`interface` 若有空的話,再寫一篇介紹`ABC`這個模組 想到這個範例的時候覺得非常適合這個模式 若在製作一些射擊遊戲的武器系統時 應該也能利用這個模式針對武器進行編寫
×
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