这次是在ASP.NET上实现四则运算,之前用策略模式实现了,所以这次想着用工厂模式实现一下。
Calculator.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 /// <summary> 7 ///Calculator 的摘要说明 8 /// </summary> 9 public class Calculator 10 { 11 // 12 //TODO: 在此处添加构造函数逻辑 13 // 14 private double a = 0; 15 private double b = 0; 16 17 public double A 18 { 19 get { return a; } 20 set { a = value; } 21 } 22 public double B 23 { 24 get { return b; } 25 set { b = value; } 26 } 27 public virtual double GetResult() 28 { 29 double result = 0; 30 return result; 31 } 32 33 } 34 35 class Add : Calculator 36 { 37 public override double GetResult() 38 { 39 double result = 0; 40 result = A + B; 41 return result; 42 } 43 } 44 45 class Sub : Calculator 46 { 47 public override double GetResult() 48 { 49 double result = 0; 50 result = A - B; 51 return result; 52 } 53 } 54 55 class Mul : Calculator 56 { 57 public override double GetResult() 58 { 59 double result = 0; 60 result = A * B; 61 return result; 62 } 63 } 64 65 class Div : Calculator 66 { 67 public override double GetResult() 68 { 69 double result = 0; 70 if (B == 0) 71 throw new Exception("除数不能为0"); 72 result = A / B; 73 return result; 74 } 75 } 76 77 public class Factory 78 { 79 public static Calculator Cal(string operate) 80 { 81 Calculator oper = null; 82 switch (operate) 83 { 84 case "+": 85 oper = new Add(); 86 break; 87 case "-": 88 oper = new Sub(); 89 break; 90 case "*": 91 oper = new Mul(); 92 break; 93 case "/": 94 oper = new Div(); 95 break; 96 } 97 return oper; 98 } 99 }
index.aspx.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 8 public partial class index : System.Web.UI.Page 9 { 10 protected void Page_Load(object sender, EventArgs e) 11 { 12 //界面加载 13 } 14 protected void Cal_Click(object sender, EventArgs e) 15 { 16 Calculator oper; 17 string strOperate = DropDownList1.SelectedItem.ToString(); 18 oper = Factory.Cal(strOperate); 19 oper.A = Convert.ToDouble(TextBox1.Text); 20 oper.B = Convert.ToDouble(TextBox2.Text); 21 string answer = Convert.ToString(oper.GetResult()); 22 23 string result = TextBox1.Text + DropDownList1.SelectedItem.ToString() + TextBox2.Text;//把运算式子存在result里面 24 if (TextBox3.Text == answer) //如果输入答案与计算出的answer相等 25 { 26 Response.Write("<script>alert('回答正确!')</script>"); //弹出回答正确 27 ListBox1.Items.Add(result + "=" + TextBox3.Text.Trim() + "√");//并把运算式子存在listbox里 28 } 29 30 else //如果答错 31 { 32 Response.Write("<script>alert('答题错误!')</script>"); //弹出答题错误 33 ListBox1.Items.Add(result + "=" + TextBox3.Text.Trim() + "×");//同样把运算式子放在listbox 34 } 35 TextBox1.Text = "";//把文本框清空,进行下一次出题 36 TextBox2.Text = ""; 37 TextBox3.Text = ""; 38 } 39 }
运行截图:
工厂方法模式。用的地方不太合适!