策略模式,ASP.NET实现

时间:2022-01-07 21:27:23

策略模式,ASP.NET实现

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; /// <summary>
///Class1 的摘要说明
/// </summary>
interface Iface
{
int Calation(int a, int b); }
public class Add:Iface
{
public int Calation(int a,int b)
{
return a+b;
}
}
public class Sub : Iface
{
public int Calation(int a, int b)
{
return a - b;
}
}
public class Mul : Iface
{
public int Calation(int a, int b)
{
return a * b;
}
}
public class Div : Iface
{
public int Calation(int a, int b)
{
if (b == )
{
throw new Exception("除数不能为零!"); } else
{
return a / b;
} }
}
public class Faction
{
private Iface iface;
public Faction(string operation)
{
switch (operation)
{
case "+":
iface = new Add();
break;
case "-":
iface = new Sub();
break;
case "*":
iface = new Mul();
break;
case "/":
iface = new Div();
break;
}
}
public int Calationss(int a, int b)
{
return iface.Calation(a, b); }
}

Default.aspx

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)
{
if (!IsPostBack)
{
ti();
}
}
public void ti()
{
Random rd = new Random();
TextBox1.Text = rd.Next(, ).ToString();
TextBox2.Text = rd.Next(, ).ToString();
string[] oper = new string[] { "+", "-", "*", "/" };
Random rdd = new Random();
Label1.Text = oper[rdd.Next(, )]; }
protected void Button1_Click(object sender, EventArgs e)
{
Faction faction = new Faction(Label1.Text);
int a = int.Parse(TextBox1.Text);
int b = int.Parse(TextBox2.Text);
string anster = faction.Calationss(a, b).ToString();
if (TextBox3.Text == anster)
{
Response.Write("回答正确!");
}
else
{
Response.Write("回答错误!");
}
TextBox3.Text = "";
ti();
}
}

测试

策略模式,ASP.NET实现策略模式,ASP.NET实现策略模式,ASP.NET实现

第一题做的是不是正确,在第二题中提示。