博客
关于我
设计模式 - 2) 策略模式
阅读量:573 次
发布时间:2019-03-10

本文共 8341 字,大约阅读时间需要 27 分钟。

// 结账基类public abstract class CashSuper{    public abstract double acceptCash(double money);}// 正常模式public class CashNomal : CashSuper{    public override double acceptCash(double money)    {        return money;    }}// 打 8 折public class CashRebate : CashSuper{    private double moneyRebate = 1d;    public CashRebate(string rebate)    {        moneyRebate = double.Parse(rebate);    }    public override double acceptCash(double money)    {        return money * moneyRebate;    }}// 满减public class CashReturn : CashSuper{    private double moneyCondition = 0.0d;    private double moneyReturn = 0.0d;    public CashReturn(string condition, string re)    {        moneyCondition = double.Parse(condition);        moneyReturn = double.Parse(re);    }    public override double acceptCash(double money)    {        if (money < moneyCondition) return money;        return money - Math.Floor(money / moneyCondition) * moneyReturn;    }}// 调用不同算法的"接口"类public class CashContext{    public CashSuper cs = null;    public CashContext(string type)    {        switch (type)        {            case "正常":                cs = new CashNomal();                break;            case "8 折":                cs = new CashRebate("0.8");                break;            case "满 200 - 50":                cs = new CashReturn("200", "50");                break;            default:                break;        }    }    public double GetResult(double money)    {        if (cs == null) return 0;        return cs.acceptCash(money);    }}// 业务通过"调用"类实现不同的算法,但内部算法具体如何实现的,外部业务不需要知道CashContext CashContextObj = new CashContext(SelectedCostType.Name);TotalPrice = CashContextObj.GetResult(double.Parse(CurPrice) * double.Parse(CurMul));

类似与简单工程,同样存在后续业务新增策略时,需要修改 CashContext 类的 CashContext(string type) 的问题,违法对修改封闭的原则;

例子:

xmal.cspublic partial class Window7 : Window{ public Window7() { InitializeComponent(); this.DataContext = new Window7ViewModel() {}; AddHandler(Button.ClickEvent, new RoutedEventHandler((this.DataContext as Window7ViewModel).Element_Click)); }}public class BindingProxy : Freezable{ protected override Freezable CreateInstanceCore() { return new BindingProxy(); } public object Data { get { return (object)GetValue(DataProperty); } set { SetValue(DataProperty, value); } } public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));}public class DelegateCommand : ICommand{ public Action ExecuteCommand = null; public Func
CanExecuteCommand = null; public event EventHandler CanExecuteChanged; public DelegateCommand() { } public DelegateCommand(Action
act) { ExecuteCommand = act; } public bool CanExecute(object parameter) { if (CanExecuteCommand != null) { return CanExecuteCommand(parameter); } else { return true; } } public void Execute(object parameter) { if (ExecuteCommand != null) this.ExecuteCommand(parameter); } public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } }}public class NotifyPropertyChanged : INotifyPropertyChanged{ public event PropertyChangedEventHandler PropertyChanged; /// /// 属性更改通知 /// /// 属性名称 public void OnProperty(string propertyname) { PropertyChangedEventHandler propertychanged = PropertyChanged; if (propertychanged != null) { propertychanged(this, new PropertyChangedEventArgs(propertyname)); } } /// /// 属性更改通知 /// ///
/// 返回属性的lambda表达式 public void RaisePropertyChange
(Expression
> func) { var body = func.Body as MemberExpression; if (body != null) { var propertyinfo = body.Member; if (propertyinfo != null) { PropertyChangedEventHandler propertychanged = PropertyChanged; if (propertychanged != null) { propertychanged(this, new PropertyChangedEventArgs(propertyinfo.Name)); } } } }}public class Window7ViewModel : NotifyPropertyChanged{ private string _CurPrice; public string CurPrice { get { return _CurPrice; } set { _CurPrice = value; RaisePropertyChange(() => CurPrice); } } private string _CurMul; public string CurMul { get { return _CurMul; } set { _CurMul = value; RaisePropertyChange(() => CurMul); } } private double _TureTotalPrice = 0.0d; ///
/// 折扣后的总价格 /// public double TureTotalPrice { get { return _TureTotalPrice; } set { _TureTotalPrice = value; RaisePropertyChange(() => TureTotalPrice); } } private double _TotalPrice = 0.0d; ///
/// 总价格 /// public double TotalPrice { get { return _TotalPrice; } set { _TotalPrice = value; RaisePropertyChange(() => TotalPrice); } } public ObservableCollection
_VList; ///
/// 所有清单 /// public ObservableCollection
VList { get { if (_VList == null) { _VList = new ObservableCollection
(); } return _VList; } set { _VList = value; RaisePropertyChange(() => VList); } } public ObservableCollection
_CostTypeList; ///
/// 所有折扣类型 /// public ObservableCollection
CostTypeList { get { if (_CostTypeList == null) { _CostTypeList = new ObservableCollection
(); } return _CostTypeList; } set { _CostTypeList = value; RaisePropertyChange(() => CostTypeList); } } public CostType SelectedCostType { get; set; } public DelegateCommand DelCommand { get; set; } public Window7ViewModel() { DelCommand = new DelegateCommand(new Action
(DelItem)); CostTypeList.Add(new CostType() { Name = "正常"}); CostTypeList.Add(new CostType() { Name = "8 折"}); CostTypeList.Add(new CostType() { Name = "满 200 - 50"}); } private void DelItem(object obj) { try { VItem item = obj as VItem; VList.Remove(item); CashContext CashContextObj = new CashContext(item.Rebate); TotalPrice -= CashContextObj.GetResult(double.Parse(item.Price) * double.Parse(item.Mul)); TureTotalPrice -= double.Parse(item.Price) * double.Parse(item.Mul); } catch (Exception ex) { } } public void Element_Click(object sender, RoutedEventArgs e) { try { UIElement element = (UIElement)e.Source; if (element == null) element = (UIElement)e.OriginalSource; if (element == null) return; switch (element.Uid) { case "Sure": if (SelectedCostType == null) { MessageBox.Show("请选择折扣"); return; } CashContext CashContextObj = new CashContext(SelectedCostType.Name); TotalPrice += CashContextObj.GetResult(double.Parse(CurPrice) * double.Parse(CurMul)); TureTotalPrice += double.Parse(CurPrice) * double.Parse(CurMul); VList.Add(new VItem() { Price = CurPrice, Mul = CurMul,Rebate = SelectedCostType.Name }); ResetCur(); break; case "Reset": VList.Clear(); ResetCur(); TotalPrice = 0; TureTotalPrice = 0; break; default: break; } } catch (Exception ex) { MessageBox.Show("出错了:" + ex); } } private void ResetCur() { CurPrice = string.Empty; CurMul = string.Empty; }}/// /// 新增的每一项/// public class VItem : NotifyPropertyChanged{ private string _Price; public string Price { get { return _Price; } set { _Price = value; RaisePropertyChange(() => Price); } } private string _Mul; public string Mul { get { return _Mul; } set { _Mul = value; RaisePropertyChange(() => Mul); } } private string _Rebate; public string Rebate { get { return _Rebate; } set { _Rebate = value; RaisePropertyChange(() => Rebate); } }}/// /// 折扣类型/// public class CostType{ public string Name { get; set; } public double Cost { get; set; }}

转载地址:http://kcuvz.baihongyu.com/

你可能感兴趣的文章
MySQL中interactive_timeout和wait_timeout的区别
查看>>
mysql中int、bigint、smallint 和 tinyint的区别、char和varchar的区别详细介绍
查看>>
mysql中json_extract的使用方法
查看>>
mysql中json_extract的使用方法
查看>>
mysql中kill掉所有锁表的进程
查看>>
mysql中like % %模糊查询
查看>>
MySql中mvcc学习记录
查看>>
mysql中null和空字符串的区别与问题!
查看>>
MySQL中ON DUPLICATE KEY UPDATE的介绍与使用、批量更新、存在即更新不存在则插入
查看>>
MYSQL中TINYINT的取值范围
查看>>
MySQL中UPDATE语句的神奇技巧,让你操作数据库如虎添翼!
查看>>
Mysql中varchar类型数字排序不对踩坑记录
查看>>
MySQL中一条SQL语句到底是如何执行的呢?
查看>>
MySQL中你必须知道的10件事,1.5万字!
查看>>
MySQL中使用IN()查询到底走不走索引?
查看>>
Mysql中使用存储过程插入decimal和时间数据递增的模拟数据
查看>>
MySql中关于geometry类型的数据_空的时候如何插入处理_需用null_空字符串插入会报错_Cannot get geometry object from dat---MySql工作笔记003
查看>>
mysql中出现Incorrect DECIMAL value: '0' for column '' at row -1错误解决方案
查看>>
mysql中出现Unit mysql.service could not be found 的解决方法
查看>>
mysql中出现update-alternatives: 错误: 候选项路径 /etc/mysql/mysql.cnf 不存在 dpkg: 处理软件包 mysql-server-8.0的解决方法(全)
查看>>