# 策略模式
属于行为型模式。
在策略模式定义了一系列算法或策略,并将每个算法封装在独立的类中,使得它们可以互相替换。通过使用策略模式,可以在运行时根据需要选择不同的算法,而不需要修改客户端代码。
策略模式包含以下几个核心角色:
- 抽象策略:定义了策略对象的公共接口或抽象类,规定了具体策略类必须实现的方法。
- 具体策略:实现了抽象策略定义的接口或抽象类,包含了具体的算法实现。
- 环境(Context):维护一个对策略对象的引用,负责将客户端请求委派给具体的策略对象执行。环境类可以通过依赖注入、简单工厂等方式来获取具体策略对象。
策略模式通过将算法与使用算法的代码解耦,提供了一种动态选择不同算法的方法。客户端代码不需要知道具体的算法细节,而是通过调用环境类来使用所选择的策略。
# 类图
- 创建接口,由具体的类实现接口
- 创建环境类
![img]()
# 代码
- 定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换
- 实现同一个接口
# 接口
|  | namespace BehavioralPatterns_StrategyPattern | 
|  | { | 
|  |     public interface Strategy | 
|  |     { | 
|  |          | 
|  |          | 
|  |          | 
|  |         public void MyStrategy(); | 
|  |     } | 
|  | } | 
# 实现接口
|  | namespace BehavioralPatterns_StrategyPattern | 
|  | { | 
|  |     public class Strategy_0 : Strategy | 
|  |     { | 
|  |         public void MyStrategy() | 
|  |         { | 
|  |             Console.WriteLine("Strategy_0"); | 
|  |         } | 
|  |     } | 
|  | } | 
|  | namespace BehavioralPatterns_StrategyPattern | 
|  | { | 
|  |     public class Strategy_1 : Strategy | 
|  |     { | 
|  |         public void MyStrategy() | 
|  |         { | 
|  |             Console.WriteLine("Strategy_1"); | 
|  |         } | 
|  |     } | 
|  | } | 
|  | namespace BehavioralPatterns_StrategyPattern | 
|  | { | 
|  |     public class Strategy_2 : Strategy | 
|  |     { | 
|  |         public void MyStrategy() | 
|  |         { | 
|  |             Console.WriteLine("Strategy_2"); | 
|  |         } | 
|  |     } | 
|  | } | 
# 环境
|  | namespace BehavioralPatterns_StrategyPattern | 
|  | { | 
|  |     public class Context | 
|  |     { | 
|  |         private Strategy MainStrategy; | 
|  |  | 
|  |         public Context(int id) | 
|  |         { | 
|  |             switch (id) | 
|  |             { | 
|  |                 case 0: | 
|  |                     MainStrategy = new Strategy_0(); | 
|  |                     break; | 
|  |  | 
|  |                 case 1: | 
|  |                     MainStrategy = new Strategy_1(); | 
|  |                     break; | 
|  |  | 
|  |                 case 2: | 
|  |                     MainStrategy = new Strategy_2(); | 
|  |                     break; | 
|  |             } | 
|  |         } | 
|  |  | 
|  |         public void GetResult() | 
|  |         { | 
|  |             MainStrategy.MyStrategy(); | 
|  |         } | 
|  |     } | 
|  | } | 
# 测试
|  | namespace BehavioralPatterns_StrategyPattern | 
|  | { | 
|  |     public class Program | 
|  |     { | 
|  |         private static void Main() | 
|  |         { | 
|  |             new Context(0).GetResult(); | 
|  |             new Context(1).GetResult(); | 
|  |             new Context(2).GetResult(); | 
|  |         } | 
|  |     } | 
|  | } | 
运行结果:
Strategy_0
Strategy_1
Strategy_2