天天看點

C#學習筆記之 政策模式

namespace 商城收銀管理
{//收費政策Context
    class CashContext
    {
        private CashSuper cs;  //聲明一個現金收費父類對象cs
        //設定政策行為,參數具體的現金收費子類(正常,打折或返利)
        public CashContext(CashSuper csuper)//通過政策方法,傳入具體的收費政策
        {
            this.cs = csuper;
        }
        
        public double GetResult(double money)
        {
            return cs.acceptCash(money);//根據收費政策的不同,獲得計算結果
        }
    }
}
           

用戶端代碼

namespace 商城收銀管理
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        double total = 0.0d;

        private void btnOk_Click(object sender, EventArgs e)
        {
            CashContext cc= null;
            switch (cbxType.SelectedItem.ToString())//根據希臘選擇框,講相應的政策對象作為參數傳入CashContect對象中
            {
                case"正常收費":
                    cc = new CashContext(new cashNormal());
                    break;
                case "滿300返100":
                    cc = new CashContext(new CashReturn("300", "100"));
                    break;
                case "打8折":
                    cc = new CashContext(new CashRebate("0.8"));
                    break;
            }
            double totalPrices = 0d;
            totalPrices = cc.GetResult(Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtNum.Text));//通過對Context的GetResult方法的調用,可以得到收取費用的結果,讓具體算法與客戶進行了隔離
            total = total + totalPrices;
            lbxList.Items.Add("單價:" + txtPrice.Text + " 數量:" + txtNum.Text + " " + cbxType.SelectedItem + " 合計:" + totalPrices.ToString());
            lblResult.Text = total.ToString();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            total = 0;
            txtPrice.Text = "1";
            txtNum.Text = "0.00";
            lbxList.Items.Clear();
            lblResult.Text = "0.00";
        }
    }
}
           

其他算法類

namespace 商城收銀管理
{
    class cashNormal:CashSuper
    {
        public override double acceptCash(double money)
        {
            return money;
        }
    }
}
namespace 商城收銀管理
{
    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;
        }
    }
}
           

繼續閱讀