策略模式是一种定义一系列算法的方法,从概念上看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。
策略模式的Strategy类层次为Context定义了一系列的可供重用的算法或行为。继承有助于析取出这些算法中的公共功能。
策略模式是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。
策略模式主要是通过提取出相同的功能进行封装,然后利用继承和多态进行完成整个过程。
下面上代码:
namespace FactoryAndStrategy
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double totalPrice = 0.0d;
private void SubmitButton_Click(object sender, EventArgs e)
{
CashContext cc = new CashContext(this.ComputerMethod.SelectedItem.ToString());
double price = Convert.ToDouble(this.PriceText.Text);
int amount = Convert.ToInt16(this.AmountText.Text);
double total = cc.ContextComputer(price,amount);
totalPrice = total + totalPrice;
this.DisplayPrice1.Items.Add("单价:" + price + " 数量:" + amount + "" + this.ComputerMethod.SelectedItem + " 合计: " + totalPrice.ToString());
this.DisplayPrice.Text = totalPrice.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
this.ComputerMethod.Items.AddRange(new string[] { "正常收费", "打8折", "打7折", "打五折" });
ComputerMethod.SelectedIndex = 0;
}
}
abstract class Strategy
{
public abstract double GetReult(double price,int amount);
}
class NormalCharge:Strategy
{
public override double GetReult(double price,int amount)
{
return price * amount;
}
}
class EightSale:Strategy
{
public override double GetReult(double price, int amount)
{
return price * amount * 0.8;
}
}
class SevenSale:Strategy
{
public override double GetReult(double price, int amount)
{
return price * amount * 0.7;
}
}
class FiveSale:Strategy
{
public override double GetReult(double price, int amount)
{
return price * amount * 0.5;
}
}
class CashContext
{
Strategy cc;
public CashContext(string str)
{
switch (str)
{
case "正常收费":
cc = new NormalCharge();
break;
case "打8折":
cc = new EightSale();
break;
case "打7折":
cc = new SevenSale();
break;
case "打五折":
cc = new FiveSale();
break;
}
}
public double ContextComputer(double price,int amount)
{
return cc.GetReult(price,amount);
}
}
}
上面显示的是一个商场打折情况,根据不同的选择计算出价格。
根据实际情况选择这种模式。