声明:以下内容来源于《大话设计模式》,学习。
策略模式:定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
商场收费策略:正常收费、打折收费、返利收费。
类图如下:
代码:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace 策略模式{ ////// MainWindow.xaml 的交互逻辑 /// public partial class MainWindow : Window { private double moneyTotal = 0d; public MainWindow() { InitializeComponent(); this.cmbType.ItemsSource = Methods.MoneyMethods; this.cmbType.SelectedIndex = 0; } ////// 确定 /// /// /// private void Button_Click_1(object sender, RoutedEventArgs e) { CashContext cs = null; switch (cmbType.SelectedItem.ToString()) { case Methods.CON_NORMAL: cs = new CashContext(new CasthNormal()); break; case Methods.CON_REBATE: cs = new CashContext( new CashRebate("0.8")); break; case Methods.CON_RETURN: cs = new CashContext( new CashReturn(300, 30)); break; } double curTotalPrices = 0d; curTotalPrices = cs.GetResult(double.Parse(txtPrice.Text.Trim()) * double.Parse(txtNum.Text.Trim())); moneyTotal += curTotalPrices; lstboxDetail.Items.Add("单价:"+txtPrice.Text.Trim()+"数量:"+txtNum.Text.Trim()+" "+cmbType.SelectedItem.ToString()+ "合计:"+curTotalPrices); txtTotal.Text = moneyTotal.ToString(); } ////// 重置 /// /// /// private void Button_Click_2(object sender, RoutedEventArgs e) { lstboxDetail.Items.Clear(); txtPrice.Text = string.Empty; txtNum.Text = string.Empty; txtTotal.Text = "0"; moneyTotal = 0d; } } #region 策略模式 ////// 抽象算法类 /// public abstract class Strategy { public abstract double AcceptCash(double money); } ////// 正常收费子类 /// public class CasthNormal : Strategy { public override double AcceptCash(double money) { return money; } } ////// 打折收费子类 /// public class CashRebate : Strategy { private double reBate = 1d; public CashRebate(string moneyRebate) { reBate = double.Parse(moneyRebate); } public override double AcceptCash(double money) { return money * reBate; } } ////// 返利子类 /// public class CashReturn : Strategy { private double moneyCondition = 0d; private double moneyReturn = 0d; public CashReturn(double moneyConditon,double moneyReturn) { this.moneyCondition = moneyConditon; this.moneyReturn = moneyReturn; } public override double AcceptCash(double money) { double moneyResult = money; if (money >= this.moneyCondition) { moneyResult = money - Math.Floor(money / moneyCondition) * moneyReturn; } return moneyResult; } } public class CashContext { private Strategy cs; public CashContext(Strategy cs) { this.cs = cs; } public double GetResult(double money) { return cs.AcceptCash(money); } } #endregion}
单价: 数量: 计算方式: 总计: 0