策略模式

 

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());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值