Loading

设计模式——策略模式的实现[备忘录]

策略模式(Strategy)

它定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。

结构图:

策略模式的实现:

一商场打折为背景:商场有正常收费,打折促销,消费多少送多少的优惠的收款方式。

抽象策略类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Strategy
{
    abstract class CashSuper
    {
        public abstract double acceptCash(double money);
    }
}

具体策略类均继承与抽象策略类:

1、正常收费类:

class CashNormal : CashSuper
    {
        public override double acceptCash(double money)
        {
            return money;
        }
    }

2、打折类:

class CashRebate : CashSuper
    {
        private double moneyRebate = 1d;

        public CashRebate(string moneyRebate)//构造函数初始化
        {
            this.moneyRebate = double.Parse(moneyRebate);
        }
        public override double acceptCash(double money)
        {
            return money * moneyRebate;
        }
    }

3、消费满多少送多少类:

class CashReturn : CashSuper
    {
        private double moneyCondition = 0.0d;
        private double moneyReturn = 0.0d;

        public CashReturn(string moneyCondition, string moneyReturn)
        {
            this.moneyCondition = double.Parse(moneyCondition);
            this.moneyReturn = double.Parse(moneyReturn);
        }
        public override double acceptCash(double money)
        {
            double result = money;
            if (money >= moneyCondition)
            {
                result = money - Math.Floor(money / moneyCondition) * moneyReturn;
                

            }
            return result;
        }
    }

4、通过简单工厂类改造的Context类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Reflection;

namespace Strategy
{
    class CashContext
    {
        CashSuper cs=null;

        //public CashContext(string type)//通过构造函数,传入具体的收费策略
        //{

        //    //this.cs = new CashRebate("0.8");
        //    string classname="Strategy.Cash"+type;
        //    this.cs = (CashSuper)Assembly.Load("Strategy").CreateInstance(classname);
      //可以通过反射类处理分支结构的

        //}

        public CashContext(string type)
        {
            switch (type)
            {
                case "正常收费":
                    CashNormal cs0 = new CashNormal();
                    cs = cs0;
                    break;
                case "满300返100":
                    CashReturn cr1 = new CashReturn("300", "100");
                    cs = cr1;
                    break;
                case "打八折":
                    CashRebate cr2 = new CashRebate("0.8");
                    cs = cr2;
                    break;

            }
        }
       
        

        public double GetResult(double money)
        {
            return cs.acceptCash(money); 
        }
    }
}

总结

    1、策略模式是一种定义一系列算法的方法,从概念上,这些算法完成的都是相同的工作,只是他们的实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。

        2、简化了单元测试。

 

       

posted @ 2012-06-07 13:30  Cooper_Liu  阅读(292)  评论(0编辑  收藏  举报