• 简单工厂模式


     Operation运算类

        class Operation
        {
            private double _numberA = 0;
            public double NumberA
            {
                get { return _numberA; }
                set { _numberA = value; }
            }
    
            private double _numberB = 0;
            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()
            {
                return NumberA + NumberB;
            }
        }
    
        class OperationSub : Operation
        {
            public override double GetResult()
            {
                return NumberA - NumberB;
            }
        }
    
        class OperationMul : Operation
        {
            public override double GetResult()
            {
                return NumberA * NumberB;
            }
        }
    
        class OperationDiv : Operation
        {
            public override double GetResult()
            {
                if (NumberB == 0)
                    throw new Exception("除数不能为0");
                return NumberA / NumberB;
            }
        }

    工厂类

        class OperationFactory
        {
            public static Operation CreateOperate(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;
            }
        }

    客户端代码

                Operation oper = OperationFactory.CreateOperate("/");
                oper.NumberA = 1;
                oper.NumberB = 0;
                double result = oper.GetResult();

    总结:

      简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。但此模式违背了开放-封闭原则。

  • 相关阅读:
    SqlLite
    C# Sqlite 序列
    C#生成条形码 Code128算法
    【Ogre Beginner Guide】第二章 OGRE场景绘图
    【Ogre Beginner Guider】第一章 配置OGRE
    用户操作体验设计——小感触
    rails 调试
    mac下安装和使用brew
    如何使用 CCache 进行 Cocos2d-x 编译加速
    AndroidStudio使用和问题记录
  • 原文地址:https://www.cnblogs.com/baiqjh/p/2840495.html
Copyright © 2020-2023  润新知