策略算法级:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StrategyDemo { abstract class Strategy { public abstract void BillInterface(); } class ConcreteStrategyA : Strategy { public override void BillInterface() { Console.WriteLine("算法A的实现"); } } class ConcreteStrategyB : Strategy { public override void BillInterface() { Console.WriteLine("算法B的实现"); } } class ConcreteStrategyC : Strategy { public override void BillInterface() { Console.WriteLine("算法C的实现"); } } }
上下文类封装简单工厂
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StrategyDemo { class Context { Strategy strategy; public const int TYPEA = 1; public const int TYPEB = 2; public const int TYPEC = 3; public Context(int i) { switch (i) { case TYPEA: strategy = new ConcreteStrategyA(); break; case TYPEB: strategy = new ConcreteStrategyB(); break; case TYPEC: strategy = new ConcreteStrategyC(); break; default: break; } } //上下文接口 public void ContextInterface() { strategy.BillInterface(); } } }
client调用:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StrategyDemo { //策略模式和简单工厂一起使用 class Program { static void Main(string[] args) { Context context; context = new Context(Context.TYPEA); context.ContextInterface(); context = new Context(Context.TYPEB); context.ContextInterface(); context = new Context(Context.TYPEC); context.ContextInterface(); Console.ReadKey(); } } }
版权声明:本文博主原创文章,博客,未经同意不得转载。
时间: 2024-10-17 16:15:39