1. 程式人生 > >設計模式之策略模式(商場打折)

設計模式之策略模式(商場打折)

Discount 類

using System;

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

namespace 策略者模式
{
    public interface IDiscountStragety
    {
        double CalculateMoney(double totalMoney); // 定義折扣
    }
    //  打八折 (超過200元)
    public class DiscountStrategyA : IDiscountStragety
    {
        public double CalculateMoney(double totalMoney)
        {
            return (totalMoney-200)>0? totalMoney* 0.8:totalMoney; //
        }
    }
    // 滿300 減50
    public class DiscountStrategyB : IDiscountStragety
    {
        public double CalculateMoney(double totalMoney)
        {
            return (totalMoney - 300) > 0 ? (totalMoney - 50) : totalMoney;
        }
    }

    // 滿三百再減50 不滿300打9折
    public class DiscountStrategyC : IDiscountStragety
    {
        public double CalculateMoney(double totalMoney)
        {
            return (totalMoney - 300) > 0 ? (totalMoney - 50) : totalMoney * 0.9;
        }
    }
    class Discount
    {
        private IDiscountStragety D_strategy;
        public Discount(IDiscountStragety discount)
        {
            this.D_strategy = discount;
        }
        public double GetMoney(double totalMoney)
        {
            return D_strategy.CalculateMoney(totalMoney);
        }
    }
}

Main():

// 商場打折促銷活動,策略1:打八折 策略:2: 滿300減50 策略3:滿300 減50元 不滿300打9折
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 策略者模式
{
    class Program
    {
        static void Main(string[] args)
        {
            Discount dd = new Discount(new DiscountStrategyA());
            Console.WriteLine("應付款{0}",dd.GetMoney(330));
            Console.WriteLine("------------------------------");
            dd = new Discount(new DiscountStrategyB());
            Console.WriteLine("應付款{0}", dd.GetMoney(330));
            Console.WriteLine("------------------------------");
            dd = new Discount(new DiscountStrategyC());
            Console.WriteLine("應付款{0}", dd.GetMoney(290));
            Console.WriteLine("------------------------------");
            Console.ReadKey();
        }
    }
}