• PHP设计模式之:工厂模式


    <?php
    abstract class Operation
    {
        public numA = 0;
        public numB = 0;
    
        public function __construct($numA, $numB)
        {
            $this->numA = $numA;
            $this->numB = $numB;
        }
        abstract function getResult();
    }
    
    class OperationAdd extends Operation
    {
        public function getResult()
        {
            return numA+numB;
        }
    }
    
    class OperationSub extends Operation
    {
        public function getResult()
        {
            return numA - numB;
        }
    }
    
    class OperationMul extends Operation
    {
        public function getResult()
        {
            return numA * numB;
        }
    }
    
    class OperationDiv extends Operation
    {
        public function getResult()
        {
            if(numB == 0)
            {
                throw new Exception("除数不能为 0 。");
            }
            return (double) (numA / numB);
        }
    }
    
    /** *************************************** */
    // 简单运算工厂类
    class OperationFactory
    {
        public static createOperate($operation, $numA, $numB)
        {
            switch($operation)
            {
                case '+':
                    $oper = new OperationAdd($numA, $numB);
                    break;
                case '-':
                    $oper = new OperationSub($numA, $numB);
                    break;
                case '*':
                    $oper = new OperationMul($numA, $numB);
                    break;
                case '/':
                    $oper = new OperationDiv($numA, $numB);
                    break;
            }
            return $oper;
        }
    
    }
    
    /** ************************ */
    // 调用方式
    $numA = 100;
    $numB = 8;
    $operation = '+';
    $oper = OperationFactory::createOperate($operation, $numA, $numB);
    echo $oper.getResult();
    

      

      

  • 相关阅读:
    iOS开发中常见错误总结(1)
    iOS开发——OC篇&纯代码退出键盘
    获取下拉框
    @RequestBody 注解
    form 表单提交
    数据库excel导出
    状态模式
    图书网上商城实现(一)
    MongoDB(一)—— 搭建环境和启动服务
    MySQL开发遇到的问题
  • 原文地址:https://www.cnblogs.com/lin3615/p/3601322.html
Copyright © 2020-2023  润新知