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());
  • 相关阅读:
    bzoj 3527: [Zjoi2014]力
    bzoj 1797: [Ahoi2009]Mincut 最小割
    bzoj 1028: [JSOI2007]麻将
    bzoj 1019: [SHOI2008]汉诺塔
    bzoj 1023: [SHOI2008]cactus仙人掌图
    bzoj 3289: Mato的文件管理
    bzoj 4034: [HAOI2015]T2
    bzoj 1218: [HNOI2003]激光炸弹
    bzoj 2431: [HAOI2009]逆序对数列
    The full stack trace of the root cause is available in the Apache Tomcat/8.0.8 logs.
  • 原文地址:https://www.cnblogs.com/buexplain/p/4600388.html
Copyright © 2011-2022 走看看