策略模式
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WindowsFormsApplication3 { abstract class CashSuper { public abstract double acceptCash(double money); } //正常消费 class CashNomal : CashSuper { public override double acceptCash(double money) { return money; } } //打折消费 class CashRebate : CashSuper { double rebate = 0; public CashRebate(double rebate) { this.rebate = rebate; } public override double acceptCash(double money) { return money * rebate; } } //满300减100 class CashReturn : CashSuper { private double moneyCondition = 0.0d; private double moneyReturn = 0.0d; public CashReturn(double condition, double dReturn) { moneyCondition = condition; moneyReturn = dReturn; } public override double acceptCash(double money) { if (money >= moneyCondition) return money - (Math.Floor(money / moneyCondition) * moneyReturn); return money; } } class CashFactory { public static CashSuper createCashAccess(string type) { CashSuper cash = null; switch (type) { case "正常收费": cash = new CashNomal(); break; case "满300返100": cash = new CashReturn(300, 100); break; case "打折": cash = new CashRebate(0.8); break; default: break; } return cash; } } class CashContext { private CashSuper cs; public CashContext(CashSuper csuper) { this.cs = csuper; } public double GetResult(double money) { return cs.acceptCash(money); } } }
调用类:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { comboBox1.Items.AddRange(new string[] { "正常收费", "满300返100", "打八折" }); comboBox1.SelectedIndex = 0; } private void button1_Click(object sender, EventArgs e) { CashContext cc = null; switch (comboBox1.SelectedItem.ToString()) { case "正常收费": cc = new CashContext(new CashNomal()); break; case "满300返100": cc = new CashContext(new CashReturn(300, 100)); break; case "打八折": cc = new CashContext(new CashRebate(0.8)); break; default: break; } double totalPrices = 0d; totalPrices = cc.GetResult(Convert.ToInt32(textBox1.Text) * Convert.ToDouble(textBox2.Text)); lblResult.Text = totalPrices.ToString(); } } }