今天研究一下策略模式。
示例程序如下:
Strategy.cs
namespace StrategyPatternExample { public interface Strategy { int Execute(int a, int b); } }
Context.cs
namespace StrategyPatternExample { public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public int ExecuteStrategy(int a, int b) { return strategy.Execute(a, b); } } }
ConcreteStrategyAdd.cs
using System; namespace StrategyPatternExample { class ConcreteStrategyAdd : Strategy { public int Execute(int a, int b) { Console.WriteLine("Called ConcreateStrategyAdd's execute. a = {0}, b = {1}", a, b); return a + b; } } }
ConcreteStrategySubtract.cs
using System; namespace StrategyPatternExample { class ConcreteStrategySubtract:Strategy { public int Execute(int a, int b) { Console.WriteLine("Called ConcreteStrategySubtract's execute, a = {0}, b = {1}",a, b); return a - b; } } }
Program.cs
using System; namespace StrategyPatternExample { class Program { static void Main(string[] args) { Context context; context = new Context(new ConcreteStrategySubtract()); int resultSub = context.ExecuteStrategy(2, 1); Console.WriteLine("ConcreteStrategySubtract's result is {0}", resultSub); Console.WriteLine(); context = new Context(new ConcreteStrategyAdd()); int resultAdd = context.ExecuteStrategy(3, 4); Console.WriteLine("ConcreteStrategyAdd's result is {0}", resultAdd); } } }
result: