Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
定义一个算法的系列,将其各个分装,并且使他们有交互性。策略模式使得算法在用户使用的时候能独立的改变。
public interface IStrategy {
int Execute(int a, int b);
}
public class AddStrategy : IStrategy {
public int Execute(int a, int b) {
return a + b;
}
}
public class SubstractStrategy : IStrategy {
public int Execute(int a, int b) {
return a - b;
}
}
public class MultiplyStrategy : IStrategy {
public int Execute(int a, int b) {
return a * b;
}
}
public class Context {
private readonly IStrategy _strategy;
public Context(IStrategy strategy) {
this._strategy = strategy;
}
public int ExecuteStrategy(int a, int b) {
return this._strategy.Execute(a, b);
}
}
class Client {
static void Main(string[] args) {
Context context;
// Three contexts following different strategies
context = new Context(new AddStrategy());
var resultA = context.ExecuteStrategy(3, 4);
Console.WriteLine(resultA);
context = new Context(new SubstractStrategy());
var resultB = context.ExecuteStrategy(3, 4);
Console.WriteLine(resultB);
context = new Context(new MultiplyStrategy());
var resultC = context.ExecuteStrategy(3, 4);
Console.WriteLine(resultC);
Console.ReadKey();
}
}
策略模式与桥模式有着相同的类图, 但是两种模式的意图是不相同的, 桥模式表示的是结构, 而策略模式表示的是行为。
策略模式中的 Context 与 Strategy 的耦合性比桥模式中的 Abstraction 与 Implementation 更紧密。