Strategy Pattern(策略模式)


1.把常變動的部分封裝起來
2.使用實作介面來建立物件
3.多用合成少用繼承

範例
Simulator.java
   1:   
   2:  public class Simulator {
   3:   
   4:      /**
   5:       * @param args
   6:       */
   7:      public static void main(String[] args) {
   8:          // TODO Auto-generated method stub
   9:          
  10:          Character sprite = new Sprite();//使用多型建立
  11:          Character normalman = new NormalMan();//同上
  12:          Character samuri = new Samuri();//同上
  13:          Character monsterboss = new MonsterBoss();//同上

  14:          //executeAttack 是 Character 類別的方法,方法內容為 ab 呼叫 attack 方法
               //而各 ab 是在每個建構子中建立不同的 ab
  15:          sprite.executeAttack();
  16:          normalman.executeAttack();
  17:          samuri.executeAttack();
  18:          
  19:          monsterboss.executeAttack();
               //動態改變 ab
  20:          monsterboss.setAttackBehavior(new AttackBySword());
  21:          monsterboss.executeAttack();
  22:          monsterboss.setAttackBehavior(new AttackByMagic());
  23:          monsterboss.executeAttack();
  24:      }
  25:   
  26:  }

Character.java

   1:   
   2:  public abstract class Character {
   3:   
   4:      AttackBehavior ab;//(攻擊行為)常變動的部分封裝成類別,宣告為介面型態可以動態改變
   5:      
   6:      public void executeAttack(){
   7:          ab.attack();
   8:      }
   9:      
  10:      public void setAttackBehavior(AttackBehavior ab){
  11:          this.ab = ab; 
  12:      }
  13:  }
  14:   
  15:  class NormalMan extends Character{
  16:      
  17:      public NormalMan(){
  18:          ab = new AttackByHand();
  19:      }
  20:  }
  21:   
  22:  class Sprite extends Character{
  23:      
  24:      public Sprite(){
  25:          ab = new AttackByMagic();
  26:      }
  27:  }
  28:   
  29:  class Samuri extends Character{
  30:      
  31:      public Samuri(){
  32:          ab = new AttackBySword();
  33:      }
  34:  }
  35:   
  36:  class MonsterBoss extends Character{
  37:      public MonsterBoss(){
  38:          ab = new AttackByHand();
  39:      }
  40:  }
如果之後還有新的角色(Character)種類,可以繼續擴充,不影響原角色類別

AttackBehavior.java

   1:   
   2:  public interface AttackBehavior {
   3:      
   4:      public void attack();
   5:  }
   6:   
   7:  class AttackByHand implements AttackBehavior{
   8:      
   9:      public void attack(){
  10:          System.out.println("AttackByHand");
  11:      }
  12:  }
  13:   
  14:  class AttackBySword implements AttackBehavior{
  15:      
  16:      public void attack(){
  17:          System.out.println("AttackBySword");
  18:      }
  19:  }
  20:   
  21:  class AttackByMagic implements AttackBehavior{
  22:      
  23:      public void attack(){
  24:          System.out.println("AttackByMagic");
  25:      }
  26:  }
如果之後有新的攻擊行為種類,可以繼續擴充,不影響原攻擊行為類別

輸出結果為

   1:  AttackByMagic
   2:  AttackByHand
   3:  AttackBySword
   4:  AttackByHand
   5:  AttackBySword
   6:  AttackByMagic




標籤: