Strategy

无论什么程序,其目的都是解决问题。而为了解决问题,我们又需要编写特定的算法。使用Strategy模式可以整体地替换算法的实现部分。能够整体地替换算法,能让我们轻松地以不同的算法去解决同一个问题,这种模式就是Strategy模式。(整体替换算法)

理清职责

  • |名字|说明

    |Hand表示猜拳游戏中的“手势”的类

    |strategy|表示猜拳游戏中的策略的类

    |Winningstrategy |表示“如果这局猜拳获胜,那么下一局也出一样的手势”这一策略的类表示“根据上一局的手势从概率上计算出下一局的手势从之前的猜拳结果计算下一局|

    |Probstrategy出各种拳的概率”这一策略的类

    |Player表示进行猜拳游戏的选手的类

    |Main测试程序行为的类

  • 具体说明

  1. 比如C++ 的STL 的Sort 以及在Java中Arrays.sort()都是可以使用策略模式来根据情况构造解决办法的
  2. 如果使用Strategy模式,在程序运行中也可以切换ConcreteStrategy角色。例如,在内存容量少的运行环境中可以使用slowButLessMemoryStrategy(速度慢但省内存的策略),而在内存容量多的运行环境中则可以使用FastButMoreMemorystrategy(速度快但耗内存的策略)。

UML

Code

  • Hand:
  1. public class Hand {
  2. // 石头
  3. private static final int HANDVALUE_GUU=0;
  4. // 剪刀
  5. private static final int HANDVALUE_GHO=1;
  6. // 布
  7. private static final int HANDVALUE_PAA=2;
  8. private static final Hand[] HANDS=new Hand[]{
  9. new Hand(HANDVALUE_GUU),
  10. new Hand(HANDVALUE_GHO),
  11. new Hand(HANDVALUE_PAA),
  12. };
  13. public static final String name[]={
  14. "石头","剪刀","布"
  15. };
  16. private int handvalue;
  17. public Hand(int handvalue) {
  18. this.handvalue = handvalue;
  19. }
  20. public static Hand getHand(int handvalue){
  21. return HANDS[handvalue];
  22. }
  23. // 胜利
  24. public boolean isStrongerThan(Hand hand){
  25. return fight(hand)==1;
  26. }
  27. // 战败
  28. public boolean isWeakerThan(Hand hand){
  29. return fight(hand)==-1;
  30. }
  31. /**
  32. * 计分: 平 0 胜1 负 -1
  33. * @param hand
  34. * @return
  35. */
  36. private int fight(Hand hand) {
  37. if(this==hand){
  38. return 0;
  39. }else if((this.handvalue+1)% 3 ==hand.handvalue){
  40. return 1;
  41. }else{
  42. return -1;
  43. }
  44. }
  45. @Override
  46. public String toString() {
  47. return name[this.handvalue];
  48. }
  49. }
  • Player
  1. public class Player {
  2. private String name;
  3. private Strategy strategy;
  4. private int wincount;
  5. private int losrcount;
  6. private int gamecount;
  7. public Player(String name, Strategy strategy) {
  8. this.name = name;
  9. this.strategy = strategy;
  10. }
  11. public Hand nextHand(){
  12. return strategy.nextHand();
  13. }
  14. /**
  15. * 分别是 胜利 负 平局
  16. */
  17. public void win(){
  18. strategy.study(true);
  19. gamecount++;
  20. wincount++;
  21. }
  22. public void lose(){
  23. strategy.study(false);
  24. losrcount++;
  25. gamecount++;
  26. }
  27. public void even(){
  28. gamecount++;
  29. }
  30. @Override
  31. public String toString() {
  32. return "Player{" +
  33. "wincount=" + wincount +
  34. ", losrcount=" + losrcount +
  35. ", gamecount=" + gamecount +
  36. '}';
  37. }
  38. }
  • ProbStrategy
  1. public class ProbStrategy implements Strategy {
  2. private Random random;
  3. public ProbStrategy(int seed) {
  4. this.random=new Random(seed);
  5. }
  6. private int pevHandValue=0;
  7. private int currentHandValue=0;
  8. private int [] [] history=new int[][]{
  9. {1,1,1},
  10. {1,1,1},
  11. {1,1,1}
  12. };
  13. /**
  14. * 如果该随机数在0至3(不含3)之间,那么出石头
  15. * 如果该随机数在3至8(不含8)之间,那么出剪刀
  16. * 如果该随机数在8至15(不含15)之间,那么出布
  17. * @return
  18. */
  19. @Override
  20. public Hand nextHand() {
  21. int bet=random.nextInt(getSum(currentHandValue));
  22. int handValue=0;
  23. if(bet<history[currentHandValue][0]){
  24. handValue=0;
  25. }else if(bet<(history[currentHandValue][0]+history[currentHandValue][1])){
  26. handValue=1;
  27. }else {
  28. handValue=2;
  29. }
  30. pevHandValue=currentHandValue;
  31. currentHandValue=handValue;
  32. return Hand.getHand(handValue);
  33. }
  34. private int getSum(int currentHandValue) {
  35. int sum=0;
  36. for (int i = 0; i < 3; i++) {
  37. sum+=history[currentHandValue][i];
  38. }
  39. return sum;
  40. }
  41. @Override
  42. public void study(boolean win) {
  43. if(win){
  44. history[pevHandValue][currentHandValue]++;
  45. }else{
  46. history[pevHandValue][(currentHandValue+1)%3]++;
  47. history[pevHandValue][(currentHandValue+2)%3]++;
  48. }
  49. }
  50. }
  • Strategy
  1. public interface Strategy {
  2. /**
  3. * nextHand方法的作用是“获取下一局要出的手势”。调用该方法后,
  4. * 实现了strategy接口的类会绞尽脑汁想出下一局出什么手势。
  5. * @return
  6. */
  7. Hand nextHand();
  8. /**
  9. *study方法的作用是学习“上一局的手势是否获胜了”。
  10. * 如果在上一局中调用nextHand方法获胜了,就接着调用study(true);
  11. * 如果输了,就接着调用study(false)。这样,Strategy接口的实现类就会改变自己的内部状态,
  12. * 从而为下一次nextHand被调用时究竟是返回“石头”“剪刀”还是“布”提供判断依据。
  13. * @param win
  14. */
  15. void study(boolean win);
  16. }
  • Winningstrategy

  1. public class Winningstrategy implements Strategy {
  2. private Random random;
  3. // 存储上一局状态
  4. private boolean won=false;
  5. private Hand preHand;
  6. /**
  7. * 有预见性的随机数种子
  8. * @param seed
  9. */
  10. public Winningstrategy(int seed) {
  11. this.random =new Random(seed);
  12. }
  13. @Override
  14. public Hand nextHand() {
  15. if (!won) {
  16. preHand= Hand.getHand(random.nextInt(3));
  17. }
  18. return preHand;
  19. }
  20. @Override
  21. public void study(boolean win) {
  22. won=win;
  23. }
  24. }
  • 测试

  1. public class MainT {
  2. public static void main(String[] args) {
  3. Player tom = new Player("tom", new Winningstrategy(2));
  4. Player cat = new Player("cat", new ProbStrategy(3));
  5. for (int i = 0; i < 100; i++) {
  6. Hand hand = tom.nextHand();
  7. Hand hand1 = cat.nextHand();
  8. if(hand.isStrongerThan(hand1)){
  9. System.out.println("tom is win");
  10. tom.win();
  11. cat.lose();
  12. }else if(hand1.isStrongerThan(hand)){
  13. System.out.println("cat is win");
  14. cat.win();
  15. tom.lose();
  16. }else{
  17. System.out.println("Even----");
  18. cat.even();
  19. tom.even();
  20. }
  21. }
  22. System.out.println(tom);
  23. System.out.println(cat);
  24. }
  25. }

策略模式(Strategy的更多相关文章

  1. 设计模式(一):“穿越火线”中的“策略模式”(Strategy Pattern)

    在前段时间呢陆陆续续的更新了一系列关于重构的文章.在重构我们既有的代码时,往往会用到设计模式.在之前重构系列的博客中,我们在重构时用到了“工厂模式”.“策略模式”.“状态模式”等.当然在重构时,有的地 ...

  2. 【转】设计模式 ( 十八 ) 策略模式Strategy(对象行为型)

    设计模式 ( 十八 ) 策略模式Strategy(对象行为型) 1.概述 在软件开发中也常常遇到类似的情况,实现某一个功能有多种算法或者策略,我们可以根据环境或者条件的不同选择不同的算法或者策略来完成 ...

  3. 设计模式 ( 十八 ) 策略模式Strategy(对象行为型)

    设计模式 ( 十八 ) 策略模式Strategy(对象行为型) 1.概述 在软件开发中也经常遇到类似的情况,实现某一个功能有多种算法或者策略,我们能够依据环境或者条件的不同选择不同的算法或者策略来完毕 ...

  4. 设计模式 - 策略模式(Strategy Pattern) 具体解释

    策略模式(Strategy Pattern) 具体解释 本文地址: http://blog.csdn.net/caroline_wendy/article/details/26577879 本文版权全 ...

  5. HeadFirst设计模式读书笔记(1)-策略模式(Strategy Pattern)

    策略模式(Strategy Pattern): 定义了了算法簇,分别封装起来,让它们之间可以相互替换,此模式让算法的变化独立于使用算法的客户端. 第一个设计原则:找出应用中可能需要变化之处,把他们独立 ...

  6. 乐在其中设计模式(C#) - 策略模式(Strategy Pattern)

    原文:乐在其中设计模式(C#) - 策略模式(Strategy Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 策略模式(Strategy Pattern) 作者:webabc ...

  7. 反馈法学习设计模式(一)——策略模式Strategy Pattern

    简介(Introduction) 之前学习Java8实战时,遇到一个很好的策略模式示例.便想着借着这个示例结合反馈式的方法来,学习策略设计模式,也以便后面反复琢磨学习. 首先我们通过练习,逐步写出符合 ...

  8. 策略模式 Strategy 政策Policy 行为型 设计模式(二十五)

    策略模式 Strategy   与策略相关的常见词汇有:营销策略.折扣策略.教学策略.记忆策略.学习策略.... “策略”意味着分情况讨论,而不是一概而论 面对不同年龄段的人,面对不同的商品,必然将会 ...

  9. 策略模式-Strategy(Java实现)

    策略模式-Strategy 在策略模式中,一个类(策略使用者)可以更改自己的执行策略. 比如以排序算法为例子, 多种排序算法都归属于排序算法, 但是实现的算法细节不同, 使用者可以很轻松地替换策略, ...

  10. [.net 面向对象程序设计深入](26)实战设计模式——策略模式 Strategy (行为型)

    [.net 面向对象程序设计深入](26)实战设计模式——策略模式 Strategy (行为型) 1,策略模式定义 策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换.策略模 ...

随机推荐

  1. noip退役赛

    上下午 6 题一起考 自闭了 T1 小明要参加一场比赛,赛制给你一个表格 $p$ ,$p_{(i,j)}$ 表示他在第 $i$ 场比赛前如果输了 $j$ 场,他这一场赢的概率,他也可以故意输掉任意多场 ...

  2. PythonPath在Windows 下的设置

    今天在调试Evernote SDK时, 遇到PythonPath的问题. 查了很多资料,有说用系统环境变量添加PythonPath, 有说在注册表中的PythonPath添加新Default字段, 但 ...

  3. NSDictionary 用法

    //Dictionary //不可变 //字典里面:是以键值对存放的 //字典存放顺序是无序的 //字典里面:value可以重复,但key不能重复 //字典里面:key一般用字符串表示,value可用 ...

  4. Poj1159 Palindrome(动态规划DP求最大公共子序列LCS)

    一.Description A palindrome is a symmetrical string, that is, a string read identically from left to ...

  5. 【转】Pro Android学习笔记(三十):Menu(1):了解Menu

    目录(?)[-] 创建Menu MenuItem的属性itemId MenuItem的属性groupId MenuItem的属性orderId MenuItem的属性可选属性 Menu触发 onOpt ...

  6. C#的闭包

    简单的理解:闭包变量是把局部变量的作用域扩展到回调函数,发生在匿名方法注册到委托上,而匿名方法中使用外部的局部变量 说什么都不如图示那么容易明白啊 先看C#的源码 class Program { st ...

  7. 4.JasperReports学习笔记4-查询数据库生成动态的报表(WEB)

    转自:http://www.blogjava.net/vjame/archive/2013/10/12/404908.html 第一种方式: sql语句中定义查询条件,报表中定义接收参数 第二种方式: ...

  8. jquery 键盘事件的使用方法详解

    转自:https://www.jb51.net/article/123579.htm jQuery处理键盘事件有三个函数,根据事件发生的顺序分别是: jquery 代码: 1.  keydown(); ...

  9. 关于request的几个字段值

    domain: localhost host: localhost:9000 url: /wechat/mynews action: WechatController.myNews path: /we ...

  10. tar压缩解压缩

    Linux下的tar压缩解压缩命令详解tar -c: 建立压缩档案-x:解压-t:查看内容-r:向压缩归档文件末尾追加文件-u:更新原压缩包中的文件 这五个是独立的命令,压缩解压都要用到其中一个,可以 ...