/**
* 面向对象计算器
* 思路:
* 1、面向对象的基本,封装、继承、多太
* 2、父类公用类
* 3、各种运算类
*/
/**
* 基类,运算类
* 只提供基本数据,不参与运算
*/
class Operation {
// 第一个数
public $first_num = 0;
// 第二个数
public $second_num = 0;
/**
* 获取结果,其他类覆盖此方法
* @return double $result
*/
public function getResult() {
$result = 0.00;
return $result;
}
}
/**
* 加法类
*/
class OperationAdd extends Operation {
/**
* 覆盖父类,实现加法算法
*/
public function getResult() {
$result = 0;
return $this->first_num + $this->second_num;
}
}
/**
* 减法类
*
*/
class OperationSub extends Operation {
/**
* 覆盖父类,实现加法算法
*/
public function getResult() {
$result = 0;
return $this->first_num - $this->second_num;
}
}
/**
* 乘法类
*
*/
class OperationMul extends Operation {
/**
* 覆盖父类,实现加法算法
*/
public function getResult() {
$result = 0;
return $this->first_num * $this->second_num;
}
}
/**
* 除类
*
*/
class OperationDiv extends Operation {
/**
* 覆盖父类,实现加法算法
*/
public function getResult() {
$result = 0;
if ($this->second_num == 0) {
throw new Exception('除法操作第二个参数不能为零!');
return 0;
}
return $this->first_num / $this->second_num;
}
}
/**
* 工厂类
*/
class OperationFactory {
/**
* 工厂函数
* @param string $operation
* @return object
*/
public function createOperation($operation) {
$oper = null;
switch($operation) {
case '+':
$oper = new OperationAdd();
break;
case '-':
$oper = new OperationSub();
break;
case '*':
$oper = new OperationMul();
break;
case '/':
$oper = new OperationDiv();
break;
default:
return 0;
}
return $oper;
}
}
$operation = new OperationFactory();
$oper = $operation->createOperation('/');
$oper->first_num = 10;
$oper->second_num = 20;
var_dump($oper->getResult());