策略模式是什麼?
策略模式定義了算法族,分別封裝起來,讓它們之間可以互相替換。此模式讓算法的變化獨立於使用算法的客戶。
爲什麼使用策略模式?
優點:
- 策略模式提供了對“開閉原則”的完美支持,用戶可以在不修改原有系統的基礎上選擇算法或行爲,也可以靈活地-增加新的算法或行爲。
- 策略模式提供了管理相關的算法族的辦法。
- 策略模式提供了可以替換繼承關係的辦法。
- 使用策略模式可以避免使用多重條件轉移語句。
- 客戶端必須知道所有的策略類,並自行決定使用哪一個策略類。
- 策略模式將造成產生很多策略類,可以通過使用享元模式在一定程度上減少對象的數量。
- 如果在一個系統裏面有許多類,它們之間的區別僅在於它們的行爲,那麼使用策略模式可以動態地讓一個對象在
- 一個系統需要動態地在幾種算法中選擇一種。
- 如果一個對象有很多的行爲,如果不用恰當的模式,這些行爲就只好使用多重的條件選擇語句來實現。
- 不希望客戶端知道複雜的、與算法相關的數據結構,在具體策略類中封裝算法和相關的數據結構,提高算法的
/** * 角色基類 */ public abstract class Character { private WeaponBehavior weapon; public abstract void fight(); public void setWeapon(WeaponBehavior weapon) { this.weapon = weapon; } public void getWeapon() { weapon.useWeapon(); } }
/** * 武器接口 */ public interface WeaponBehavior { void useWeapon(); }
/** * 國王 */ public class King extends Character { @Override public void fight() { System.out.println("I'm the King.My attract force is 95."); } }
/** * 皇后 */ public class Queen extends Character { @Override public void fight() { System.out.println("I'm the Queen.My attract force is 90."); } }
/** * 騎士 */ public class Knight extends Character { @Override public void fight() { System.out.println("I'm the Knight.My attract force is 92.5."); } }
/** * 妖怪 */ public class Troll extends Character { @Override public void fight() { System.out.println("I'm the troll.My attract force is 100."); } }
/** * 實現用寶劍揮舞 */ public class SwordBehavior implements WeaponBehavior{ @Override public void useWeapon() { System.out.println("I use the sword to attract."); } }
/** * 實現用匕首刺殺 */ public class KnifeBehavior implements WeaponBehavior { @Override public void useWeapon() { System.out.println("I use the knife to attract."); } }
/** * 實現用弓箭射擊 */ public class BowAndArrowBehavior implements WeaponBehavior { @Override public void useWeapon() { System.out.println("I use the bow and arrow to attract."); } }
/** * 實現用斧頭劈砍 */ public class AxeBehavior implements WeaponBehavior { @Override public void useWeapon() { System.out.println("I use the axe to attract."); } }
public class TestTroll { public static void main(String[] args) { Character character = new Troll(); character.setWeapon(new AxeBehavior()); character.fight(); character.getWeapon(); } }
I'm the troll.My attract force is 100.
I use the axe to attract.
總結:我們知道該對象是狗,但是我們現在利用animal進行多態的調用。
更棒的是,子類實例化的動作不再需要在代碼中硬編碼,例如 new Dog(),而是“在運行時才指定具體實現的對象”。