用封装,继承,多态 实现计算器功能
面向对象的编程,并不是类越多越好,类的划分是为了封装,但分类的基础是抽象,具有相同属性和功能的对象的抽象集合才是类
属性类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace factoryClass.simpleness { /// <summary> /// 属性类 /// </summary> public class Operation { private double _numberA = 0; private double _numberB = 0; public double NumberA { get { return _numberA;} set { _numberA = value; } } public double NumberB { get { return _numberB; } set { _numberB = value; } } public virtual double GetResult() { double result = 0; return result; } } }
加法类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace factoryClass.simpleness { /// <summary> /// 加法类 /// </summary> public class OperationAdd :Operation { public override double GetResult() { double result = 0d; result = NumberA + NumberB; return result; } } }
除法类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace factoryClass.simpleness { /// <summary> /// 除法类 /// </summary> public class OperationDivide : Operation { public override double GetResult() { double resule = 0d; if (NumberB == 0) { return resule; } else { resule = NumberA / NumberB; } return resule; } } }
乘法类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace factoryClass.simpleness { /// <summary> /// 乘法类 /// </summary> public class OperationMultiply:Operation { public override double GetResult() { double result = 0d; result = NumberA * NumberB; return result; } } }
减法类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace factoryClass.simpleness { /// <summary> /// 减法类 /// </summary> public class OperationSubtract:Operation { public override double GetResult() { double result = 0d; result = NumberA - NumberB; return result; } } }
简单工厂类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace factoryClass.simpleness { /// <summary> /// 运算类 /// </summary> public class OperationFactory { /// <summary> /// 运算符 /// </summary> /// <param name="operation"></param> /// <returns></returns> public static Operation CreateOperation(string operation) { Operation oper = null; switch (operation) { case"+": oper = new OperationAdd(); break; case"-": oper = new OperationSubtract(); break; case"*": oper = new OperationMultiply(); break; case"/": oper = new OperationDivide(); break; } return oper; } } }
客户端
factoryClass.simpleness.Operation oper; oper = factoryClass.simpleness.OperationFactory.CreateOperation(this.txtopertion.Text); oper.NumberA = Convert.ToDouble(this.txtnumberA.Text); oper.NumberB = Convert.ToDouble(this.txtnumberB.Text); this.txtresult.Text = oper.GetResult().ToString();