大话设计模式之简单工厂模式代码

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

namespace 简单工厂模式
{
    //operation 运算类
    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;
            if (NumberB != 0)
            {
                result = NumberA / NumberB;
                return result;
            }
            else
            {
                throw new Exception("除数不能为0。");
            }
        }
    }
    //简单运算工厂类
    public class OperationFactory
    {
        public static operation  createOperation(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;
            }
            return oper;
        }

    }


    class Program
    {
        static void Main(string[] args)
        {
            operation oper; 
            oper = OperationFactory.createOperation("/");
            oper.NumberA = 23;
            oper.NumberB = 1;
            double result = oper.GetResult();
        }
    }
}

你可能感兴趣的:(大话设计模式之简单工厂模式代码)