ASP.net四则运算《《《策略模式

Calculator.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
///Calculator 的摘要说明
/// </summary>
public abstract class Calculator
{
public abstract double Cal(double x, double y);
} public class Add : Calculator //接口法运算
{
public override double Cal(double x, double y) //重写
{
double result = ;
result = x + y;
return result;
}
}
public class Sub : Calculator
{
public override double Cal(double x, double y)
{
double result = ;
result = x - y;
return result;
}
}
public class Mul : Calculator
{
public override double Cal(double x, double y)
{
double result = ;
result = x * y;
return result;
}
}
public class Div : Calculator
{
public override double Cal(double x, double y)
{
double result = ;
result = x / y;
return result;
}
}
public class Opear //定义运算符
{
private Calculator calculate = null; //实例化一个基类的引用对象
public Opear(Calculator calculator) //calculator为派生类的一个对象
{
this.calculate = calculator; //把派生类的对象赋给基类的引用对象
}
public double Cal(double x, double y, String op)
{
return this.calculate.Cal(x, y); //返回计算结果
}
}

ASP.net后台代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void Button1_Click(object sender, EventArgs e)
{
string op = DropDownList1.SelectedItem.ToString();
double x = Convert.ToDouble(TextBox1.Text);
double y = Convert.ToDouble(TextBox2.Text); Opear opear =null;
if (DropDownList1.SelectedIndex == )
{
opear = new Opear(new Add());
}
else if (DropDownList1.SelectedIndex == )
{
opear = new Opear(new Sub());
}
else if (DropDownList1.SelectedIndex == )
{
opear = new Opear(new Mul());
}
else if (DropDownList1.SelectedIndex == )
{
opear = new Opear(new Div());
}
string answer = opear.Cal(x, y, op).ToString();
string result = TextBox1.Text + DropDownList1.SelectedItem.ToString() + TextBox2.Text;
if (TextBox4.Text == answer)
{
Response.Write("<script>alert('回答正确!')</script>");
ListBox1.Items.Add(result + "=" + TextBox4.Text.Trim());
} else
{
Response.Write("<script>alert('答题错误!')</script>");
ListBox1.Items.Add(result + "=" + TextBox4.Text.Trim());
}
TextBox1.Text = "";
TextBox2.Text = "";
TextBox4.Text = "";
}
}

运行结果:

运行界面:

ASP.net四则运算《《《策略模式

ASP.net四则运算《《《策略模式ASP.net四则运算《《《策略模式

上一篇:.net MVC 微信公众号 获取 access_token


下一篇:map,set的模板[STL]