您的位置:首页 > 编程语言 > Java开发

java设计模式(5) - 策略者模式

2015-08-06 20:55 369 查看
概念:定义一系列算法,把它们一个个封装起来,并且使它们可互相替换。该模式使得算法可独立于使用它的客
户而变化。

场景:Joe上班的公司做了一套相当成功的模拟鸭子游戏,游戏中会出现各种鸭子,一边游泳戏水,一边呱呱叫,系统的内部设计使用了标准的OO技术,设计了一个鸭子超类,并让各种鸭子继承此超类。后来需求改变又需要加飞的功能。
传统上当鸭子接到不现指令后,根据指令做出不再的动作。 用switch去判断指令,每当要加新的功能,就需要改动原代码中的switch分支。

作用:在不改变原代码的情况下,为程序添加新的功能。

步骤:
1. 定义一个行为的接口
2. 写不同的实现类实现具体的行为
3. 在鸭子实体中维护一个map集合去存放这些具体的行为
4.使用时根据不同的命令执行不同的操作,

示例

/**
 * 定义行为的接口
 * @author jiangwei
 *
 */
public interface IBehavior {
 void execute();
}

==================================
/**
 * 走的能力
 * @author jiangwei
 *
 */
public class GoBehavior implements IBehavior{

 public void execute() {
  System.out.println("走");
 }

}
==================================================
/**
 * 飞的能力
 * @author jiangwei
 *
 */
public class FlyBehavior implements IBehavior{
 public void execute() {
  System.out.println("飞");
 }
}
===========================================================
/**
 * 跑的能力
 * @author jiangwei
 *
 */
public class RunBehavior implements IBehavior{

 public void execute() {
  System.out.println("跑");
 }

}

===================================================
public class YaZi {
 
 //能力的集合
 private static Map<String, IBehavior> behaviors = new HashMap<String, IBehavior>();
 
 static {
  behaviors.put("fly", new FlyBehavior());
  behaviors.put("go", new GoBehavior());
  behaviors.put("run", new RunBehavior());
 
 }
 
 public void execute(String commond) {
  IBehavior behavior = behaviors.get(commond);
  if(behavior != null) {
   behavior.execute();
  } else {
   System.out.println("不会");
  }
 }
}

======================================================
public class Client {
 public static void main(String[] args) {
  YaZi yaZi = new YaZi();
  yaZi.execute("fly");
  yaZi.execute("go");
  yaZi.execute("run");
  yaZi.execute("xx");
 }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  策略者模式