标签:
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
/// <summary> /// 抽象策略角色 /// </summary> public interface IStrategy { void DoSomething(); } /// <summary> /// 具体策略角色1 /// </summary> public class ConcreteStrategy1 : IStrategy { public void DoSomething() { Console.WriteLine("策略1"); } } /// <summary> /// 具体策略角色2 /// </summary> public class ConcreteStrategy2 : IStrategy { public void DoSomething() { Console.WriteLine("策略2"); } } /// <summary> /// 封装角色 /// </summary> public class Content { private IStrategy strategy; public Content(IStrategy strategy) { this.strategy = strategy; } public void Doanything() { this.strategy.DoSomething(); } }
static void Main(string[] args) { Content content = new Content(new ConcreteStrategy2()); content.Doanything(); content = new Content(new ConcreteStrategy1()); content.Doanything(); }
标签:
原文地址:http://www.cnblogs.com/zhangzhi19861216/p/4970743.html