您的位置:首页 > 其它

简单工厂模式

2015-06-25 17:05 260 查看
/**
* 计算器
* @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());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: