zoukankan      html  css  js  c++  java
  • 简单工厂模式

     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();

    总结:

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

  • 相关阅读:
    Linux 基础 —— RPM
    mysql主从复制
    mysql.user表中Host为%的含义
    MySQL + Atlas --- 部署读写分离(参考02)
    MySQL读写分离技术(参考)
    蚁群算法
    java 回调
    java 接口sort comparable
    matlab 求解高阶方程
    matlab 求解常微分方程
  • 原文地址:https://www.cnblogs.com/baiqjh/p/2840495.html
Copyright © 2011-2022 走看看