1、封装
首先是新建一个运算类(Calcultor.cs),它包含两个属性strNumA和strNumB,用以储存计算时的两个数,此外,还有一个虚方法Getresult(),用以得到运算的结果。
public class calculator { /// <summary> /// 定义运算类的属性 /// </summary> private double dblNumA = 0,dblNumB=0; /// <summary> /// 定义属性dblNumA的操作方法 /// </summary> public double dblnuma { get { return dblNumA; } set { dblNumA = value; } } /// <summary> /// 定义属性dblNumB的操作方法 /// </summary> public double dblnumb { get { return dblNumB; } set { dblNumB = value; } } /// <summary> /// 得到运算结果 /// </summary> /// <returns>dblresult</returns> public virtual string GetResult() { string dblResult ="0"; return dblResult; } }
2、继承
然后将操作加、减、乘、除写成运算类的子类,继承运算类后重写Getresult()。
/// <summary> /// 加法类 /// </summary> class OperationAdd : calculator { public override string GetResult() { string dblresult = "0"; dblresult = (dblnuma + dblnumb).ToString(); return dblresult; } } /// <summary> /// 减法类 /// </summary> class OperationSub : calculator { public override string GetResult() { string dblresult = "0"; dblresult = (dblnuma - dblnumb).ToString(); return dblresult; } } /// <summary> /// 乘法类 /// </summary> class OperationMul : calculator { public override string GetResult() { string dblresult = "0"; dblresult = (dblnuma * dblnumb).ToString(); return dblresult; } } /// <summary> /// 除法类 /// </summary> class OperationDiv : calculator { public override string GetResult() { string dblresult = "0"; if (dblnumb != 0) { dblresult = (dblnuma / dblnumb).ToString(); } else { dblresult = "除数不能为0!"; } return dblresult; } }
3、多态
再用一个单独的类创造实例的过程。
public class factory { public static calculator createOperation(string strOperation) { calculator cal = null; switch (strOperation) { case "+": { cal = new OperationAdd(); break; } case "-": { cal = new OperationSub(); break; } case "*": { cal = new OperationMul(); break; } case "/": { cal = new OperationDiv(); break; } } return cal; } }