码迷,mamicode.com
首页 > 其他好文 > 详细

简单工厂模式

时间:2016-09-08 00:30:47      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

    /// <summary>
    /// 操作基类
    /// </summary>
    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()
        {
            return 0;
        }
    }

    /// <summary>
    /// 具体操作类
    /// </summary>
    public class OperationAdd : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA + NumberB;
            return result;
        }
    }


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

    /// <summary>
    /// 工厂根据需求生产某一类型的事物
    /// </summary>
    public class OperationFactory
    {
        public static Operation createOperation(string operate)
        {
            Operation func = null;
            switch(operate)
            {
                case "+":
                    func = new OperationAdd();
                    break;
                case "-":
                    func = new OperationSub();;
                    break;
            }

            return func;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var operation = OperationFactory.createOperation("+");
            operation.NumberA = 10;
            operation.NumberB = 5;
            operation.GetResult();
        }
    }

 

简单工厂模式

标签:

原文地址:http://www.cnblogs.com/Daniel-Liang/p/5851415.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!