码迷,mamicode.com
首页 > 其他好文 > 详细

策略模式

时间:2015-12-06 17:45:39      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

fengzhuang.cs

技术分享
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;

  public abstract class fengzhuang
 {
     public abstract double Cal(double a, double b);
 }
 public class Add : fengzhuang      
 {
     public override double Cal(double a, double b)
     {
         double result = 0;
         result = a + b;
         return result;
     }
 }
 public class Sub : fengzhuang
 {
     public override double Cal(double a, double b)
     {
         double result = 0;
         result = a - b;
         return result;
     }
 }
 public class Mul :fengzhuang
 {
     public override double Cal(double a, double b)
     {
         double result = 0;
         result = a * b;
         return result;
} } public class Div : fengzhuang { public override double Cal(double a, double b) { double result = 0; result = a / b; return result; } } public class Context { private fengzhuang calculate = null; public Context(Calculator _cal) { this.calculate = _cal; } public double Cal(double a, double b, String symbol) { return this.calculate.Cal(a, b); } }

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Cal_Click(object sender, EventArgs e)
{
string symbol = DropDownList1.SelectedItem.ToString();
double a = Convert.ToDouble(TextBox1.Text);
double b = Convert.ToDouble(TextBox2.Text);
Context contex = null;
if (DropDownList1.SelectedIndex == 1)
{
contex = new Context(new Add()); 
}
else if (DropDownList1.SelectedIndex == 2)
{
contex = new Context(new Sub()); 
}
else if (DropDownList1.SelectedIndex == 3) 
{
contex = new Context(new Mul()); 
}
else if (DropDownList1.SelectedIndex == 4) 
{
contex = new Context(new Div()); 
}
string answer = contex.Cal(a, b, symbol).ToString();

string result = TextBox1.Text + DropDownList1.SelectedItem.ToString() + TextBox2.Text;
if (TextBox3.Text == answer)
{
Response.Write("<script>alert(‘回答正确!‘)</script>");
ListBox1.Items.Add(result + "=" + TextBox3.Text.Trim());
}

else 
{
Response.Write("<script>alert(‘答题错误!‘)</script>");
ListBox1.Items.Add(result + "=" + TextBox3.Text.Trim() );
}
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
}
}

总结:看来想做成功还得伙伴。要想走得快一个人走,但要想走得远还得伙伴挽着手一起走。有人帮忙就是好

策略模式

标签:

原文地址:http://www.cnblogs.com/zj15517225953/p/5023903.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!