1. 程式人生 > >使用面向物件的程式設計思想寫一個簡單的控制檯計算器程式,放鬆一下

使用面向物件的程式設計思想寫一個簡單的控制檯計算器程式,放鬆一下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Calculator2
{
    class Program
    {
        static void Main(string[] args)
        {
            Operation oper;
            oper = OperationFactory.createOpearate("+");
            Console.WriteLine("請輸入_numberA:");
            oper.NumberA =Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("請輸入_numberB:");
            oper.NumberB =Convert.ToDouble(Console.ReadLine());
            double result = oper.GetResult();
            Console.WriteLine("結果是:{0}",result);
            Console.ReadLine();
        }
    }

    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;
        }
    }

    class OperationAdd : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA + NumberB;
            return result;
        }
    }

    class OperationSub : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA - NumberB;
            return result;
        }
    }

    class OperationMul : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA * NumberB;
            return result;
        }
    }

    class OperationDiv : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA / NumberB;
            return result;
        }
    }

    public class OperationFactory
    {
        public static Operation createOpearate(string operate)
        {
            Operation oper = null;
            switch (operate)
            {
                case "+":
                    oper = new OperationAdd();
                    break;
                case "-":
                    oper = new OperationSub();
                    break;
                case "*":
                    oper = new OperationMul();
                    break;
                case "/":
                    oper = new OperationDiv();
                    break;
                default:
                    break;
            }
            return oper;
        }

    }
}