ASP.NET中实现封装与策略模式
首先把运算方法封装起来,这样在网页界面中直接就可以调用了,不过是换张脸而已!
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> ///jisuan 的摘要说明 /// </summary> public abstract class jisuanqi //抽象类 { public abstract int jisuan(int left, int right);//抽象方法 } public class jia : jisuanqi //加法类继承抽象类 { public override int jisuan(int left, int right)//重写抽象方法 { int jieguo = 0; jieguo = left + right; return jieguo; } } public class jian : jisuanqi { public override int jisuan(int left, int right) { int jieguo = 0; jieguo = left - right; return jieguo; } } public class cheng : jisuanqi { public override int jisuan(int left, int right) { int jieguo = 0; jieguo = left * right; return jieguo; } } public class chu : jisuanqi { public override int jisuan(int left, int right) { int jieguo = 0; jieguo = left / right; return jieguo; } } public class Context//上下文 { private jisuanqi jsq = null;//基类引用对象 public Context(jisuanqi jsp) { this.jsq = jsp; //派生类对象jsp赋给基类对象jsq } public int jisuan(int left, int right, string fuhao) { return this.jsq.jisuan(left,right); } }
界面后台代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void jisuan_Click(object sender, EventArgs e) { string fuhao = DropDownList1.SelectedItem.ToString(); int left = Convert.ToInt32(TextBox1.Text); int right = Convert.ToInt32(TextBox2.Text); Context contex = null; if (DropDownList1.SelectedIndex == 1) { contex = new Context(new jia()); } else if (DropDownList1.SelectedIndex == 2) { contex = new Context(new jian()); } else if (DropDownList1.SelectedIndex == 3) { contex = new Context(new cheng()); } else if (DropDownList1.SelectedIndex == 4) { contex = new Context(new chu()); } string daan = contex.jisuan(left,right,fuhao).ToString(); string result = TextBox1.Text + DropDownList1.SelectedItem.ToString() + TextBox2.Text; if (TextBox3.Text == daan) { Response.Write("回答正确!"); } else { Response.Write("回答错误!"); } } }
运行测试:
答对有提示回答正确:
答错提示回答错误: