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

    /**
     * 计算器
     * @param  $op_num_1 操作数1
     * @param  $op_num_2 操作数2
     * @param  $op_str   操作符
     * @return 操作结果
     */
    function op($op_num_1,$op_num_2,$op_str) {
        $fun = op_factory($op_str);
        return $fun($op_num_1,$op_num_2);
    }
    /**
     * 我他丫无法描述该函数
     * @param  $op_str 操作符
     * @return 具体执行操作的函数
     */
    function op_factory($op_str) {
        switch ($op_str) {
            case '+':
                return 'op_add';
                break;
            default:
                return 'op_subtract';
                break;
        }
    }
    /**
     * 加法
     */
    function op_add($op_num_1,$op_num_2) {
        return $op_num_1 + $op_num_2;
    }
    /**
     * 减法
     */
    function op_subtract($op_num_1,$op_num_2) {
        return $op_num_1 - $op_num_2;
    }
    
    echo op(100,50,'-'),'<br/>';
    
    //----------------我--------是--------分--------割--------线----------------
    
    /**
     * 计算器工厂
     */
    class op_factory {
        public static function create_op($op_str) {
            switch ($op_str) {
                case '+':
                    return new op_add();
                    break;
                default:
                    return new op_subtract();
                    break;
            }
        }
    }
    /**
     * 计算器
     */
    abstract class op {
        public $op_num_1 = 0; //操作数1
        public $op_num_2 = 0; //操作数2
        abstract function get_result();
    }
    /**
     * 加法
     */
    class op_add extends op {
        public function get_result() {
            return $this->op_num_1 + $this->op_num_2;
        }
    }
    /**
     * 减法
     */
    class op_subtract extends op {
        public function get_result() {
            return $this->op_num_1 - $this->op_num_2;
        }
    }
    
    $op = op_factory::create_op('+'); //通过工厂生成对象
    $op->op_num_1 = 100;
    $op->op_num_2 = 50;
    print_r($op->get_result());
  • 相关阅读:
    pyhanlp 实体命名识别
    NABCD需求分析
    源代码
    遇到的问题和解决方法
    运行及总结
    测试与调试
    读《一个程序猿的生命周期》和《人,绩效和职业道德》有感
    面向对象程序设计
    设计类图
    SRS文档
  • 原文地址:https://www.cnblogs.com/buexplain/p/4600388.html
Copyright © 2011-2022 走看看