1. 程式人生 > >初識設計模式(策略模式)

初識設計模式(策略模式)

set 實現 string .com int 輸出結果 print 結果 ont

  前言:學會總結,學會記錄,與大家分享,也希望大家可以指正錯誤的地方。  

  為什麽要學設計模式?因為在工作中,感到力不從心了,想重構卻無從下手,所以借此讓設計模式進入到我的大腦中。

 策略模式(Strategy)

  定義了算法族,分別封裝起來,讓它們之間可以互相替換,此模式讓算法的變化獨立於使用算法的客戶。

  我認為策略模式就是讓變化的地方獨立起來,不是采用抽象類的繼承,而是使用接口編程,從而達到可維護、可擴展的目的,並在程序運行時也可以動態改變其行為。但是使用這些策略類的客戶,必須理解這些策略類並自己決定使用哪一個策略類。簡單來說就是策略模式封裝了變化(算法)。

技術分享圖片

  代碼實現

  舉個例子:多個遊戲角色,可以使用不同的武器,每個角色一次只能使用一種武器,但是可以在遊戲過程中換武器。

技術分享圖片

 1 /**
 2  * 策略模式實現
 3  * Created by yule on 2018/6/23 12:29.
 4  */
 5 public class Demo1 {
 6     public static void main(String[] args){
 7         Character character = new King(new KnifeBehavior());
 8         character.fight();
 9 
10         character = new
Queen(new SwordBehavior()); 11 character.fight(); 12 13 character = new Knight(new AxeBehavior()); 14 character.fight(); 15 16 character = new Troll(new BowAndArrowBehavior()); 17 character.fight(); 18 } 19 } 20 21 /** 22 * 抽象算法類 Strategy 23 */ 24 abstract
class WeaponBehavior{ 25 public abstract void useWeapon(); 26 } 27 28 class KnifeBehavior extends WeaponBehavior{ 29 @Override 30 public void useWeapon() { 31 System.out.println("用匕首"); 32 } 33 } 34 35 class SwordBehavior extends WeaponBehavior{ 36 @Override 37 public void useWeapon() { 38 System.out.println("用寶劍"); 39 } 40 } 41 42 class AxeBehavior extends WeaponBehavior{ 43 @Override 44 public void useWeapon() { 45 System.out.println("用斧頭"); 46 } 47 } 48 49 class BowAndArrowBehavior extends WeaponBehavior{ 50 @Override 51 public void useWeapon() { 52 System.out.println("用弓箭"); 53 } 54 } 55 56 /** 57 * Context 58 * 角色 59 */ 60 class Character{ 61 WeaponBehavior weaponBehavior; 62 63 public void setWeaponBehavior(WeaponBehavior weaponBehavior){ 64 this.weaponBehavior = weaponBehavior; 65 } 66 67 public void fight(){ 68 this.weaponBehavior.useWeapon(); 69 } 70 } 71 72 class King extends Character{ 73 public King(WeaponBehavior weaponBehavior){ 74 super(); 75 super.setWeaponBehavior(weaponBehavior); 76 } 77 } 78 79 class Queen extends Character{ 80 public Queen(WeaponBehavior weaponBehavior){ 81 super(); 82 super.setWeaponBehavior(weaponBehavior); 83 } 84 } 85 86 class Knight extends Character{ 87 public Knight(WeaponBehavior weaponBehavior){ 88 super(); 89 super.setWeaponBehavior(weaponBehavior); 90 } 91 } 92 93 class Troll extends Character{ 94 public Troll(WeaponBehavior weaponBehavior){ 95 super(); 96 super.setWeaponBehavior(weaponBehavior); 97 } 98 }

輸出結果:

技術分享圖片

  參考書籍:《Head First 設計模式》《大話設計模式》

初識設計模式(策略模式)