工厂模式

复制代码

本人qq群也有许多的技术文档,希望可以为你提供一些帮助(非技术的勿加)。

QQ群:   281442983 (点击链接加入群:http://jq.qq.com/?_wv=1027&k=29LoD19)    QQ:1542385235

/**
 * 计算器
 * @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());

本人qq群也有许多的技术文档,希望可以为你提供一些帮助(非技术的勿加)。

QQ群:   281442983 (点击链接加入群:http://jq.qq.com/?_wv=1027&k=29LoD19)    QQ:1542385235

 

我的淘宝店,可以进去逛逛噢:https://shop108912636.taobao.com/index.htm?spm=2013.1.w5001-7867000954.3.1d29318dPlLar7&scene=taobao_shop

 

posted @ 2015-06-25 17:51  piwenfei  阅读(213)  评论(0编辑  收藏  举报