你的位置:首页 > 软件开发 > ASP.net > 设计模式之策略模式(包含与简单工厂模式的区别,实现了超市结账系统)

设计模式之策略模式(包含与简单工厂模式的区别,实现了超市结账系统)

发布时间:2016-05-07 12:00:07
今天看了策略模式,不知觉的和前天学的简单工厂模式做了对比,也百度了一些博客,最后的出一个结论,简单工厂模式主要负责初始化各种对象,而策略模式则是更多的对方法进行封装。同一个例子,如果使用简单工厂模式,则是根据需求返回不同的对象,而使用策略模式的话,就是根据需求来返回不同的方法。下 ...

今天看了策略模式,不知觉的和前天学的简单工厂模式做了对比,也百度了一些博客,最后的出一个结论,简单工厂模式主要负责初始化各种对象,而策略模式则是更多的对方法进行封装。同一个例子,如果使用简单工厂模式,则是根据需求返回不同的对象,而使用策略模式的话,就是根据需求来返回不同的方法。

下面的例子分别使用简单工厂模式和策略模式和写的超市结账系统,二者功能实现上没有区别。

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Draget='_blank'>wing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace 简单工厂模式与策略模式{  public class Cash  {    double price;    int num;    public double Price    {      get      {        return price;      }      set      {        price = value;      }    }    public int Num    {      get      {        return num;      }      set      {        num = value;      }    }    public virtual string GetCash()    {      return "error";    }  }  public class CashA:Cash  {    public override string GetCash()    {      return (Price * Num).ToString();    }  }  public class CashB : Cash  {    public override string GetCash()    {      return (Price * Num*0.8).ToString();    }  }  public class CashC : Cash  {    public override string GetCash()    {      return (Price * Num * 0.5).ToString();    }  }  public class CashFactory     //工厂类  {    public static Cash GetCashObject(string str)    {      switch (str)      {        case "正常收费": return new CashA();        case "8折收费": return new CashB();        case "5折收费": return new CashC();        default: return new Cash();      }    }  }  public partial class Form1 : Form  {    public Form1()    {      InitializeComponent();    }    double total=0;    private void button1_Click(object sender, EventArgs e)    {      double totalPrice;      Cash p = CashFactory.GetCashObject(comboBox1.SelectedItem.ToString());      p.Num = int.Parse(textBox2.Text);      p.Price = double.Parse(textBox1.Text);      totalPrice=double.Parse(p.GetCash());      total+=totalPrice;      listBox1.Items.Add("单价:"+textBox1.Text+"数量:"+textBox2.Text+"总价为"+totalPrice.ToString());      label4.Text = total.ToString();    }    private void button2_Click(object sender, EventArgs e)    {      textBox1.Text = null;      textBox2.Text = null;      label4.Text = null;      for (int i = 0; i < listBox1.Items.Count;i++ )      {        listBox1.Items.RemoveAt(i);      }    }    private void Form1_Load(object sender, EventArgs e)    {      comboBox1.Items.AddRange(new object[] { "正常收费", "8折收费", "5折收费" });      comboBox1.SelectedIndex = 0;    }  }}

原标题:设计模式之策略模式(包含与简单工厂模式的区别,实现了超市结账系统)

关键词:设计模式

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。