详细请看:https://www.runoob.com/design-pattern/strategy-pattern.html
什么是策略模式???
在策略模式(Strategy Pattern)中一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
在策略模式定义了一系列算法或策略,并将每个算法封装在独立的类中,使得它们可以互相替换。通过使用策略模式,可以在运行时根据需要选择不同的算法,而不需要修改客户端代码。
在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。
解决了什么问题
解决在多种相似算法存在时,使用条件语句(如if…else)导致的复杂性和难以维护的问题。
缺优点
优点
- 算法切换自由:可以在运行时根据需要切换算法。
- 避免多重条件判断:消除了复杂的条件语句。
- 扩展性好:新增算法只需新增一个策略类,无需修改现有代码。
缺点
- 策略类数量增多:每增加一个算法,就需要增加一个策略类。
- 所有策略类都需要暴露:策略类需要对外公开,以便可以被选择和使用。
使用建议
:::danger
- 当系统中有多种算法或行为,且它们之间可以相互替换时,使用策略模式。
- 当系统需要动态选择算法时,策略模式是一个合适的选择。
:::
具体实现
- 定义策略接口:所有策略类都将实现这个统一的接口。
- 创建具体策略类:每个策略类封装一个具体的算法或行为。
- 上下文类:包含一个策略对象的引用,并通过该引用调用策略。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public interface IStrategy { int DoOperation(int num1, int num2); }
public class OperationAdd : IStrategy {
public int DoOperation(int num1, int num2) { return num1 + num2; } } public class OperationSubtract : IStrategy { public int DoOperation(int num1, int num2) { return (num1 - num2); } }
public class OperationMultiply : IStrategy { public int DoOperation(int num1, int num2) { return (num1 * num2); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Context { private IStrategy strategy;
public Context(IStrategy strategy) { this.strategy = strategy; } public void ExecuteOperation(int num1 , int num2) { Debug.Log( strategy.DoOperation(num1,num2 )); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public enum StrategyType { Add, Subtract, Multiply } public StrategyType strategyType; private Context context;
void Start() { if (strategyType == StrategyType.Add) { context = new Context(new OperationAdd()); } else if (strategyType == StrategyType.Subtract) { context = new Context(new OperationSubtract()); } context.ExecuteOperation(5, 5);
}
|