public abstract class Calculator { public double Number1 { get; set; } public double Number2 { get; set; } public abstract double Calculate(); }
class Add : Calculator { public Add(double n1,double n2) { this.Number1 = n1; this.Number2 = n2; } public override double Calculate() { return Number1 + Number2; } }
class Sub : Calculator { public Sub(double n1,double n2 ) { this.Number1 = n1; this.Number2 = n2; } public override double Calculate() { return Number1 - Number2; } }
class Program { static void Main(string[] args) { Console.WriteLine("第一个数"); double Number1 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("操作符"); string Operate= Console.ReadLine(); Console.WriteLine("第二个数"); double Number2= Convert.ToDouble(Console.ReadLine()); Calculator calculator = null; switch (Operate) { case "+": calculator = new Add(Number1, Number2); break; case "-": calculator = new Sub(Number1, Number2); break; } if (calculator!=null) { Console.WriteLine("结果是:{0}",calculator.Calculate()); } else { Console.WriteLine("没有这种操作"); } } }
优化:
Calculator calculator = GetComputeObject(Operate, Number1, Number2);
private static Calculator GetComputeObject(string perate, double number1, double number2) { Calculator result = null; switch (perate) { case "+": result = new Add(number1, number2); break; case "-": result = new Sub(number1, number2); break; } return result; }