1.功能类
namespace Data
{
/*
* 策略模式和简单工厂模式相比,少了使用switch case 做判断,然后去实例化相应的
* 对象,比简单工厂模式更灵活。 它们代码的区别就在于此处使用了抽象类代替工厂类
*/
/// <summary>
/// 策略类
/// </summary>
public abstract class Strategy
{
//操作策略
public abstract string OperateStrategy();
}
/// <summary>
/// 添加
/// </summary>
public class InsertStrategy : Strategy
{
public override string OperateStrategy()
{
NorthwindEntities db = new NorthwindEntities();
Employees e = new Employees();
e.LastName = "chuanshi_yoyo_yoyo";
e.FirstName = "zhushao";
db.AddToEmployees(e);
db.SaveChanges();
return "添加数据成功";
}
}
/// <summary>
/// 删除
/// </summary>
public class DelStrategy : Strategy
{
public override string OperateStrategy()
{
NorthwindEntities db = new NorthwindEntities();
Employees e = db.Employees.Where(c => c.EmployeeID == 19).FirstOrDefault();
db.DeleteObject(e);
db.SaveChanges();
return "删除数据成功";
}
}
/// <summary>
/// 修改
/// </summary>
public class UpdateStrategy : Strategy
{
public override string OperateStrategy()
{
NorthwindEntities db = new NorthwindEntities();
Employees e = db.Employees.Where(c => c.EmployeeID == 19).FirstOrDefault();
e.LastName = "chuanshi_yoyo_yoyo";
db.SaveChanges();
return "修改数据成功";
}
}
}
2.策略中心类,负责具体策略类的创建
namespace Data
{
/// <summary>
/// 策略中心,负责具体策略的创建
/// </summary>
public class StrategyCenter
{
Strategy strategy;
//使用具体的策略实例化策略中心
public StrategyCenter(Strategy strategyObj)
{
strategy = strategyObj;
}
//执行操作
public string ExecOperate()
{
return strategy.OperateStrategy();
}
}
}
3.操作调用
StrategyCenter center = new StrategyCenter(new InsertStrategy());
Console.WriteLine(center.ExecOperate());