設計模式(Design Pattern)學習心得彙整:策略模式(Strategy Pattern)

我覺得完整的學習,
需要透過整理和實作把知識內化。

這是我學習設計模式(Design Pattern)的心得彙整

Summarized the knowledge and implement it is the best way to learn new things. 
The summary is how I realize the Design Pattern.

====本文開始====

參考的資料來源(Reference):阿洲的程式教學-設計模式(Design Pattern)

策略模式(Strategy Pattern)

簡單說就是透過虛擬化(virtual)以及依賴注入的方式,
降低子類別繼承父類別時的function耦合度。

In short, the strategy pattern is a pattern that can de-couple the functions between father class and child class when Inheritance.
And the de-coupling skills are Virtual-Function and Dependency Injection.

範例說明:
文章中用的是戰士/魔法師/龍騎士,
這些職業都繼承遊戲的基本腳色設定,
具有的基本技能包含:攻擊/飛行/防禦。

差異A:龍騎士會飛,戰士不會飛
差異B:戰士進行物理攻擊,魔法師進行魔法攻擊

Example:
The samples in the reference article are Warrior, Magician, and DragonRider.
These careers are all Inheritance in the basic role setting including Attack, Fly, and Defence.

Difference A: Dragonriders Can fly, but Warriors Can't.
Difference B: Warriors do Physical attack, but Magicians do Magic attack.

解決方法:
1. 腳色設定(基礎類別)具有基礎功能的宣告,但對有歧異的功能,宣告為虛擬(virtual)功能,例如:攻擊行為(AttackBehavior)。
2. 宣告獨特功能繼承基礎類功能,例如:魔法攻擊(MagicAttack)繼承攻擊行為,物理攻擊(NormalAttack)也繼承攻擊行為,記得實作功能。
3. 宣告職業時,傳入基礎功能類別。
4. 執行階段產生職業時,依照職業類別船入對應的攻擊行為,例如魔法師傳入魔法攻擊,戰士傳入物理攻擊。

Solutions:
1. Declare basic function in Basic Class(Role Setting), and declare a basic function as virtual function when may have some different behaviors. ex. AttackBehavior.
2. Declare various function and inheritance in the basic function. Ex. MagicAttack inheritance in the AttackBehavior, NormalAttack inheritance in the AttackBehavior also. Don't forget to implement the various functions.
3. Declare the career class, and declare the basic class.

4. New the career object at runtime and inject the various functions. Ex. When new the Magician should inject the MagicAttack function, and inject the NormalAttack function when new the Warrior. 

好處:
1. 降低繼承關係的耦和度
2. 提高程式的彈性:增加職業時,不需要重新實作所有的功能,例如:若龍騎士為新增職業,其攻擊行為只要傳入物理攻擊(已實作)即可

Advantages:
1. De-couple the inheritance relationship.
2. Increase code flexibility: Don't have to implement all functions every time when we want to create a new career. Ex. If we create a new career called Dragon Knight, we could inject the NormalAttack directly.

記憶方式:
當我們覺得某個人運用某個策略去完成某些事情,
就是一種依照不同情境拿出不同策略來對應的概念,
對應到策略模式(Strategy Pattern),
就是依照不同職業(情境)要傳入(拿出)不同獨特功能(策略)來對應的概念。

Memorize tips:
When we say someone is strategic, it means he or she handles different situations with different strategies.
According to this concept, the Strategy Pattern is injecting (handling) different careers(situations) with different functions (strategies).