Westward Design - Strategy Pattern

Record Westward design study. Westward design patterns pdf Share: https://pan.baidu.com/s/11h9x-4RffXydf3GFH5_y7g  extraction code: x5c3.

Previous learned by example the supermarket checkout preferential algorithm package and produce examples of simple plants . This is a simple plant to continue working on and let it become a strategy mode.

Each algorithm is a specific preferential policies, they abstracted a common strategy is to return the amount of the bill. Created by CashContext instance, call strategy, simplifying the coupling between classes and algorithms using an algorithm class. Here the client knows the specific use of a different kind of strategy, and even check out whether the amount calculated by the mixing of several strategies (for example: Incoming "full 900 by 100; 20%" on the use of CashRebate and CashReturn).

using System;

namespace ConsoleApp4
{
    class Program
    {
        public static void Main(string[] args)
        {
            var cashContext = new CashContext("8折");
            var result = cashContext.GetResult(900);
        }
    }

    public class CashContext
    {
        CashSuper cashSuper;
        public CashContext(string type)
        {
            switch (type)
            {
                case "满300减50": cashSuper = new CashReturn(300d, 50d); break;
                case "8折": cashSuper = new CashRebate(0.8d); break;
                default: cashSuper = new CashNormal(); break;
            }
        }
        public double GetResult(double money)
        {
            return cashSuper.AcceptCash(money);
        }
    }

    public abstract class CashSuper
    {
        public abstract double AcceptCash(double money);
    }

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

    public class CashRebate : CashSuper
    {
        private double rebate;

        public CashRebate(double rebate)
        {
            this.rebate = rebate;
        }

        public override double AcceptCash(double money)
        {
            return money * rebate;
        }
    }

    public class CashReturn : CashSuper
    {
        private double moneyCondition;
        private double moneyReturn;
        public CashReturn(double condition, double @return)
        {
            moneyCondition = condition;
            moneyReturn = @return;
        }
        public override double AcceptCash(double money)
        {
            if (money >= moneyCondition)
            {
                return money - ((money / moneyCondition) * moneyReturn);
            }
            else
            {
                return money;
            }
        }
    }    
}

 

Guess you like

Origin www.cnblogs.com/bibi-feiniaoyuan/p/strategy.html