欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

封装计算方法实现面向对象计算器。

程序员文章站 2022-10-01 11:03:23
优化: Calculator calculator = GetComputeObject(Operate, Number1, Number2); ......
 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;
        }