策略模式是一种对象的行为型模式,定义一系列算法,并将每一个算法封装起来,并让它们可以相互替换。策略模式比算法独立于使用它的客户而变化,其目的是将行为和环境分隔,当出现新的行为时,只需要实现新的策略类。
优点:
1)另一种子类化方法。
2)在类自身中定义了每一个行为,这样就减少了条件语句。
3)更容易扩展模型。在不对应用程序进行代码修改的情况下,使该模式具有新的行为。
使用场景:
1)许多相关类只是在行为方面有所区别。
2)许多算法的不同变体。
3)算法使用客户端未知的数据。
Strategy 模式
public class Hand { public const int HANDVALUE_GUU = 0;//石头 public const int HANDVALUE_CHO = 1;//剪刀 public const int HANDVALUE_PAA = 2;//布 private int handvalue; private Hand(int handvalue) { this.handvalue = handvalue; } public static Hand[] hands = { new Hand(HANDVALUE_GUU), new Hand(HANDVALUE_CHO), new Hand(HANDVALUE_PAA) }; /// <summary> /// 从值获得对象实例 /// </summary> /// <param name="handvalue"></param> /// <returns></returns> public static Hand GetHand(int handvalue) { return hands[handvalue]; } }
public interface Strategy { Hand NextHand(); }
public class WinningStrategy : Strategy { private bool won = false; private Hand prevHand; private Random random = new Random(); public Hand NextHand() { if (!won) { prevHand = Hand.GetHand(random.Next(3)); } Console.WriteLine("调用了WinningStrategy策略"); return prevHand; } }
public class ProbStrategy : Strategy { public Hand NextHand() { int handvalue = 0; //省略具体实现 Console.WriteLine("调用了ProbStrategy策略"); return Hand.GetHand(handvalue); } }
public class Player { private string name; private Strategy strategy; public Player(string name, Strategy strategy) { this.name = name; this.strategy = strategy; } /// <summary> /// 向战略请示手势 /// </summary> /// <returns></returns> public Hand NextHand() { return strategy.NextHand(); } }
class Program { static void Main(string[] args) { //策略模式 while (true) { Console.WriteLine("/r/n请选择:1、WinningStrategy策略游戏;2、ProbStrategy策略游戏..."); string line = Console.ReadLine(); if (line.Equals("1")) { Strategy.Strategy strategy = new WinningStrategy(); Player player = new Player("abc", strategy); player.NextHand(); } else if (line.Equals("2")) { Strategy.Strategy strategy = new ProbStrategy(); Player player = new Player("abc", strategy); player.NextHand(); } } } }