Strategy 模式
目录:
AbstractPunish.cs;//抽象策略类
Context.cs;//管理类
LaJiaoShui.cs;//具体策略类
LaoHuDeng.cs;//具体策略类
XiaZhuQian.cs;//具体策略类
Program.cs.//客户端类
//AbstractPunish.cs;
namespace StrategyPunish
{
abstract class Punish
{
public abstract void PunishMethod();
}
}
//Context.cs;
namespace StrategyPunish
{
//策略Context
class PunishContext
{
//声明一个父类对象
private Punish punish = null;
//设置策略行为,参数为具体的
//public PunishContext(Punish punish)
//{
// this.punish = punish;
//}
public PunishContext(string type)
{
switch (type)
{
case "ljs":
punish = new LaJiaoShui();
break;
case "lhd":
punish = new LaoHuDeng();
break;
case "xzq":
punish = new XiaZhuQian();
break;
}
}
//得到结果(利用了多态机制,不同的策略行为导致不同的结果)
public void GetResult()
{
if (punish != null)
{
punish.PunishMethod();
}
else
{
Console.WriteLine("输入非法");
}
}
}
}
//LaJiaoShui.cs;
namespace StrategyPunish
{
//正常,继承Punish
class LaJiaoShui : Punish
{
public override void PunishMethod()
{
Console.WriteLine("LaJiaoShui!");
}
}
}
//LaoHuDeng.cs;
namespace StrategyPunish
{
//正常,继承Punish
class LaoHuDeng : Punish
{
public override void PunishMethod()
{
Console.WriteLine("LaoHuDeng!");
}
}
}
//XiaZhuQian.cs;
namespace StrategyPunish
{
//正常,继承Punish
class XiaZhuQian : Punish
{
public override void PunishMethod()
{
Console.WriteLine("XiaZhuQian!");
}
}
}
//Program.cs.
namespace StrategyPunish
{
class Program
{
static void Main(string[] args)
{
//PunishContext pc;
//pc = new PunishContext(new LaJiaoShui());
//pc.GetResult();
//pc = new PunishContext(new LaoHuDeng());
//pc.GetResult();
//pc = new PunishContext(new XiaZhuQian());
//pc.GetResult();
while (true)
{
string strAha = Console.ReadLine();
PunishContext pc;
pc = new PunishContext(strAha);
pc.GetResult();
}
}
}
}