设计模式

设计模式 - 策略模式

2016-01-23  本文已影响47人  Mitchell

using System;
namespace Strategy
{
    //支付 Base 类
    abstract class CashSuper
    {
        public abstract double acceptMoney(double money);
    }
    //普通 支付
    class CashNormal : CashSuper
    {
        private double money  = 1d;
        public CashNormal(double money){
            this.money = money;         
        }
        public override double acceptMoney(double money){
            return this.money;
        }
    }
    //支付返现
    class CashReturn: CashSuper
    {
        private double fullMoney = 0d;
                double returnMoney = 0d;
        public CashReturn(double fullM,double returnM){
            this.returnMoney = returnM;
            this.fullMoney = fullM;
        }
        public override double acceptMoney(double money){
            if (money >= fullMoney) {
                return money - this.returnMoney;
            } else {
                return money;
            }
        }
    }
    //打折
    class CashRebate: CashSuper
    {
        private double moneyRebate = 1d;
        public CashRebate(string moneyRebate){
            this.moneyRebate = double.Parse(moneyRebate);
        }
        public override double acceptMoney(double money){
            return money*this.moneyRebate;
        }
    }
    //暴露给客户端的接口设计类
    class CashContext
    {
        CashSuper strategy = null;
        public CashContext(double money){
            CashNormal cs = new CashNormal(money);
            this.strategy = cs;
        }
        public CashContext(string rebate)
        {
            CashRebate cs = new CashRebate (rebate);
            this.strategy = cs;
        }
        public CashContext(double returnM,double fullM)
        {
            CashReturn cs = new CashReturn (fullM, returnM);
            this.strategy = cs;
        }
        public double GetResult(double money){
            return this.strategy.acceptMoney(money);
        }
    }
      //使用方式
    class MainClass
    {
        public static void Main (string[] args)
        {
            CashContext a =new CashContext(1000,200);
            double r = a.GetResult (1200);
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读