首页 > 代码库 > 简单工厂模式实例

简单工厂模式实例

运算类

public class operation    {        private double a = 0;        private double b = 0;        public double A        {            get { return a; }            set { a = value; }        }        public double B        {            get { return b; }            set { b = value; }        }        public virtual double GetResult()        {            double rst = 0;            return rst;        }    }

 加减乘除类

public class Jia : operation     {        public override double GetResult()        {            double result = 0;            result = A + B;            return result;        }    }    public class Jian : operation     {        public override double GetResult()        {            double result = 0;            result = A - B;            return result;        }    }    public class Cheng : operation    {        public override double GetResult()        {            double result = 0;            result = A * B;            return result;        }    }    public class Chu : operation    {        public override double GetResult()        {            double result = 0;            if(B==0)                throw new Exception("除数不能为0");            result = A / B;            return result;        }    }

 工厂类

public class OperationFactory    {        public static operation CreateOperation(string operation)        {            operation result = null;            switch (operation)            {                case "+": result = new Jia(); break;                case "-": result = new Jian(); break;                case "*": result = new Cheng(); break;                case "/": result = new Chu(); break;                default:                    break;            }            return result;        }    }

 控制台请求

 
            Console.Write("请输入第一个数");            double a =Convert.ToDouble(Console.ReadLine());            Console.Write("请输入第二个数");            double b =Convert.ToDouble(Console.ReadLine());            Console.Write("请输入运算符");            string opr = Console.ReadLine();            operation opr2 = OperationFactory.CreateOperation(opr);            opr2.A = a;            opr2.B = b;            double result = opr2.GetResult();            Console.WriteLine(result);            Console.ReadLine();


 

简单工厂模式实例