asp.net

一、封装

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

/// <summary>
///Class1 的摘要说明
/// </summary>
public class Calculator
{
public Calculator()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public abstract class Calculator
{
public abstract double But(double a, double b);
}

public class Add : Calculator //接口法运算
{
public override double But(double a, double b) //重写
{
double result = 0;
result = a + b;
return result;
}
}
public class Sub : Calculator
{
public override double But(double a, double b)
{
double result = 0;
result = a - b;
return result;
}
}
public class Mul : Calculator
{
public override double But(double a, double b)
{
double result = 0;
result = a * b;
return result;
}
}
public class Div : Calculator
{
public override double But(double a, double b)
{
double result = 0;
result = a / b;
return result;
}
}
public class Every //定义运算符
{
private Calculator calculate = null; //实例化一个基类的引用对象
public Every(Calculator ca) //calculator为派生类的一个对象
{
this.calculate = ca; //把派生类的对象赋给基类的引用对象
}
public double But(double a, double b, String c)
{
return this.calculate.But(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 _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{

string c = DropDownList1.SelectedItem.ToString();
double a = Convert.ToDouble(TextBox1.Text);
double b = Convert.ToDouble(TextBox2.Text);
Every every =null;
if (DropDownList1.SelectedIndex == 1)
{
every = new Every(new Add());
}
else if (DropDownList1.SelectedIndex == 2)
{
every = new Every(new Sub());
}
else if (DropDownList1.SelectedIndex == 3)
{
every = new Every(new Mul());
}
else if (DropDownList1.SelectedIndex == 4) {
every = new Every(new Div());
}
string answer = every.But(a, b, c).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 = "";
}
}

 三、实现

总结:做了这两次作业我总结出来面向对象编程,并不是类越多越好,类的划分是为了封装,但分类的基础是抽象,具有相同属性和功能的对象的抽象集合才是类。

总体感受就那么多,其实还是对这些模式不熟悉不理解,还要好好学

 

posted @ 2015-12-06 15:08  嘿,MyDarling  阅读(136)  评论(2编辑  收藏  举报