.NET设计模式之简单工厂模式

2019/7/21 16:18:27 人评论 次浏览 分类:学习教程

原文链接:http://www.cnblogs.com/LifeDecidesHappiness/p/10368123.html
1.代码结构

2.Operation.cs
using System;

namespace CalculatorDemoWithMindOfObject
{
    public class Operation
    {
        public double NumberA { get; set; }
        public double NumberB { get; set; }

        public virtual double GetResult()
        {
            double result = 0;
            return result;
        }
    }

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

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

    public class OperationDiv : Operation
    {
        public override double GetResult()
        {
            if (NumberB == 0)
            {
                throw new Exception("除数不能为0");
            }
            double result = 0;
            result = NumberA / NumberB;
            return result;
        }
    }
}
3.OperationFactory.cs
namespace CalculatorDemoWithMindOfObject
{
    /// <summary>
    ///     运算类工厂(简单工厂模式)
    /// </summary>
    public class OperationFactory
    {
        public static Operation CreateOperation(string operatorInfo)
        {
            Operation operation = null;
            switch (operatorInfo)
            {
                case "+":
                    operation = new OperationAdd();
                    break;

                case "-":
                    operation = new OperationSub();
                    break;

                case "*":
                    operation = new OperationMul();
                    break;

                case "/":
                    operation = new OperationDiv();
                    break;
            }
            return operation;
        }
    }
}
4.Program.cs
using System;

namespace CalculatorDemoWithMindOfObject
{
    /// <summary>
    ///     使用面向对象三大特征(封装、继承、多态)实现的计算器
    ///     LDH @ 2019-2-12
    /// </summary>
    class Program
    {
        static void Main()
        {
            Console.Title = "使用面向对象三大特征,实现简单的计算器功能";

            Operation op = OperationFactory.CreateOperation("+");
            op.NumberA = 10;
            op.NumberB = 20;

            double result = op.GetResult();
            Console.WriteLine("运算结果:" + result);

            Console.ReadKey();
        }
    }
}
5.运行结果

转载于:https://www.cnblogs.com/LifeDecidesHappiness/p/10368123.html

相关资讯

    暂无相关的资讯...

共有访客发表了评论 网友评论

验证码: 看不清楚?
    -->