# 前言 系列第四篇 練習的是策略模式(Strategy Pattern) # 策略模式 一種行為型設計模式,它允許定義一系列可互換的演算法或策略,並讓客戶端在運行時可以自由選擇使用哪一種策略,而無需修改使用它們的代碼。 策略模式的核心思想是將演算法的定義與使用分開,將不同的演算法封裝在獨立的類別中,並且可以在運行時根據需要切換這些演算法。 假設我正在玩一款射擊遊戲 有把神奇的槍接受各種口徑的子彈 不同口徑的子彈會有不一樣的傷害與穿透能力 實作此功能就可以使用策略模式 ```python= from abc import ABC, abstractmethod class Bullet(ABC): # 定義抽象的子彈類別及必須實作的屬性 @abstractmethod def __init__(self, damage: int = 0, penetration: int = 0) -> None: self.damage = damage self.penetration = penetration # 穿透力 # 依照不同口徑給予不同的傷害與穿透力 class Caliber556(Bullet): def __init__(self) -> None: super().__init__(40, 1) class Caliber762(Bullet): def __init__(self) -> None: super().__init__(70, 3) class Caliber9(Bullet): def __init__(self) -> None: super().__init__(30, 0) class Gun(): # 實作使用不同口徑的武器 def __init__(self, bullet_type: Bullet) -> None: self.bullet_type = bullet_type def power_info(self) -> str: return f"this gun damage is {self.bullet_type.damage}, and penetration power is {self.bullet_type.penetration}." if __name__ == '__main__': caliber_556 = Gun(Caliber556()) print(caliber_556.power_info()) caliber_762 = Gun(Caliber762()) print(caliber_762.power_info()) caliber_9 = Gun(Caliber9()) print(caliber_9.power_info()) ``` 最後的輸出結果為 ``` this gun damage is 40, and penetration power is 1. this gun damage is 70, and penetration power is 3. this gun damage is 30, and penetration power is 0. ``` # 心得 總體來說實作並不難 依舊是想到實際的案例比較困難一些
×
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