本文主要是介绍【设计模式】——策略模式之赌球风波,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
前提摘要:
今天晚上世界杯进行淘汰赛,一场重头戏是巴西队和智利队。小华是内马尔的粉丝,他希望巴西队能赢,小玉认为智利队是黑马,能赢巴西队。于是二人打赌,赌资为每个球10元,比如两队进5球,则输的一方需出50元;小华又加了一条,如果内马尔进球则赌资加10元;小玉又加了一条,如果两队90分钟之内打平,需点球决胜负,则说明两队实力相近,赌资减少20%
策略模式:
围绕赌资的多少,抽象出一个父类,然后三个具体算法类继承父类,再用一个策略选择类为算法类和界面类承上启下,界面部分根据相应要求给出代码!结构图为:
编写代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace 策略模式
{public partial class 赌球那点事 : Form{public 赌球那点事(){InitializeComponent();}//赌资抽象类abstract class CashSuper{public abstract double acceptCash(double money);}//正常情况下赌资子类class CashNormal : CashSuper{public override double acceptCash(double money){double result = money;return money;}}//内马尔进球后的赌资class CashAdd : CashSuper{private double goalsNeymar = 0.0d;private double moneyAdd = 0.0d;public CashAdd(string goalsNeymar, string moneyAdd){this.goalsNeymar = double.Parse(goalsNeymar);this.moneyAdd = double.Parse(moneyAdd);}public override double acceptCash(double money){double result = money;if (goalsNeymar > 0)result = money + goalsNeymar * moneyAdd;return result;}}//90分钟未分胜负,需点球时赌资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;}}//CashContext类class CashContext{private CashSuper cs;public CashContext(CashSuper csuper){this.cs = csuper;}public double GetResult(double money){return cs.acceptCash(money);}}
private void button3_Click(object sender, EventArgs e){double total = 0.0d;CashContext cc = null;switch (cmbType.SelectedItem .ToString()){case "正常计算":cc = new CashContext(new CashNormal());break;case "内马尔进球":cc = new CashContext(new CashAdd("1", "10"));break;case "点球大战":cc = new CashContext(new CashRebate("0.8"));break;}double totalPrices = 0d;totalPrices = cc.GetResult (Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtNum.Text));total = total + totalPrices;txtShow.Text = "单价:" + txtPrice.Text + "进球数:" + txtNum.Text+ " " + cmbType.SelectedItem + " 合计:" + totalPrices.ToString();label10.Text = total.ToString();}private void 赌球那点事_Load(object sender, EventArgs e){cmbType.Items.AddRange(new object[] { "正常计算", "内马尔进球", "点球大战" });cmbType.SelectedIndex = 0;}}
}
假如巴西3:2智利,内马尔有进球,则:
这场赌球风波到底结局如何,再过几个小时就知道了!
这篇关于【设计模式】——策略模式之赌球风波的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!