以运算器为例,通常编译运算器的时候直接在主函数中直接写代码,这样对以后的修改和重复调用产生了很大的麻烦,所以一定要将所有的功能封装成多个类,无论以后修改还是添加功能都方便了许多。
运算器的简单工厂模式代码:
基类:
public class operation
{
private double num_a;
public double Num_a
{
get { return num_a; }
set { num_a = value; }
}
private double num_b;
public double Num_b
{
get { return num_b; }
set { num_b = value; }
}
public virtual double getreault()
{
double result = 0;
return result;
}
}
因为所有的功能都包括共有的两个操作数,一个结果,所以任何运算都可以继承这个基类,省去 重复声明等步骤,要注意任何需要被继承的类都需要加上virtual,然后在子类中加 override 重 写这个类。
加法运算类(只举例一个,其他运算都一样)
class operaAdd:operation
{
public override double getreault()
{
double result = 0;
result = Num_a + Num_b;
return result;
}
}
加法运算继承了运算基类,父类中的变量直接用,然后重写getresult()方法使其变成加法运算。
(其他运算代码相似)
简单工厂类:
public class opreaFactory
{
public static operation createOpera(string opera)
{
operation oper = null;
switch (opera)
{
case "+":
oper = new operaAdd();
break;
case "-":
oper = new operaSum();
break;
case "*":
oper = new operaMul();
break;
case "/":
oper = new operaDiv();
break;
}
return oper;
}
}
这里需要特别注意声明的方法的类型是 operation类的类型,这样这样再返回时,直接就将运算类返回,也就是实例好的oper,否则别的类型不能返回这个oper。这样很方便(个人理解)
客户端类
private void btn_op_Click(object sender, EventArgs e)
{
if (txt_op.Text.Trim() != "")
{
operation oper = null;
oper = opreaFactory.createOpera(txt_op.Text);
double result = 0;
oper.Num_a=Convert.ToDouble(txt_num1.Text);
oper.Num_b=Convert.ToDouble(txt_num2.Text);
result = oper.getreault();
txt_result.Text = result.ToString();
}
运算过程:
先传递给opreaFactory.createOpera一个参数比如“+”在opreaFactory.createOpera中将oper实例到加法的类中,然后返回这个实例。在将operation中的参数赋值,然后调用运算方法返回结果。
注意:声明的是静态方法,调用静态方法不是用实例化后的类对象来调用,而是用
类名.方法名 这样调用。要是不想那样调用 就把static 关键字去掉。