首页 > 代码库 > 策略模式和简单工厂
策略模式和简单工厂
策略算法类:
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(); } } }
客户端调用:
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(); } } }
策略模式和简单工厂
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。