初学设计模式【1】策略模式——Strategy Pattern

推荐大家阅读:《head first 设计模式》,下面总结的内容主要是从这本书中来的,加上自己的理解加以整理。

开始之前

  OO基础:抽象、封装、多态、继承

  OO原则:封装变化;多用组合少用继承;针对接口(superType)不针对实现编程

定义

  defines a family of algorithms,encapsulates each one,and makes them interchangeable.Strategy lets the algorithm vary independently from clients that use it.定义算法簇,分别封装起来,让它们之间可以相互替换,此模式让算法的变换独立于使用算法的客户。

设计谜题

  有一个动作冒险游戏,有三个游戏角色King,Queen,Soldier。有三种武器gun,knife,Sword.每个角色一次只能使用一种武器,但可以在游戏过程中切换武器。

  你的任务:利用策略模式设计UML类图

(取自书中的一个章末练习加以精简)

UML图

说明:

  a.分离变化与不变的部分,Character中封装不变的部分,WeaponBehavior中封装将来可能发生变化的部分

  b.Character中持有WeaponBehavior接口(针对接口编程),此处接口指超类型,比如还可以是抽象类

  c.通过WeaponBehavior隔离武器实现类的变化。

关键代码:

1.Character类

Character
 1 public abstract class Charactor {
 2     private WeaponBehavior wb;
 3 
 4     public void setWb(WeaponBehavior wb) {
 5         this.wb = wb;
 6     }
 7 
 8     public abstract void disPlay();
 9 
10     public void fight() {
11         disPlay();
12         wb.useWeapon();
13     }
14 }

2.WeaponBehavior接口

public interface WeaponBehavior {
    public void useWeapon();
}

3.King类

 1 public class King extends Charactor {
 2 
 3     public King() {
 4         setWb(new GunBehavior());
 5     }
 6 
 7     @Override
 8     public void disPlay() {
 9         System.out.println("I am King");
10     }
11 
12 }

4.Queen类

 1 public class Queen extends Charactor {
 2 
 3     public Queen() {
 4         setWb(new KnifeBehavior());
 5     }
 6 
 7     @Override
 8     public void disPlay() {
 9         System.out.println("i am Queen");
10     }
11 
12 }

5.Soldier类

 1 public class Soldier extends Charactor {
 2 
 3     public Soldier() {
 4         setWb(new SwordBehavior());
 5     }
 6 
 7     @Override
 8     public void disPlay() {
 9         System.out.println("i am Soldier");
10     }
11 
12 }

6.具体武器类

View Code
 1 public class SwordBehavior implements WeaponBehavior {
 2 
 3     @Override
 4     public void useWeapon() {
 5         System.out.println(" Sword ");
 6     }
 7 
 8 }
 9 
10 //***********************************************
11 
12 
13 public class KnifeBehavior implements WeaponBehavior {
14 
15     @Override
16     public void useWeapon() {
17         System.out.println(" Knife ");
18     }
19 
20 }
21 
22 //***********************************************
23 
24 public class GunBehavior implements WeaponBehavior {
25 
26     @Override
27     public void useWeapon() {
28         System.out.println(" Gun ");
29     }
30 
31 }

7.测试类

import org.junit.Test;

public class TestStrategy {

    @Test
    public void test() {
        Charactor c = new Queen();
        WeaponBehavior wb = new SwordBehavior();
        c.setWb(wb);
        c.fight();
    }

}

代码下载: http://www.kuaipan.cn/file/id_132249327308375054.htm

原文地址:https://www.cnblogs.com/byghui/p/3035309.html