用简单工厂模式实现两个数的加减乘除
<?php
/**
* @desc 简单工厂模式
*/
/**
* @desc 运算类
*/
abstract class Operation {
private $numberA = 0;
private $numberB = 0;
public function getNumberA() {
return $this->numberA;
}
public function getNumberB() {
return $this->numberB;
}
public function setNumberA($numberA) {
$this->numberA = $numberA;
}
public function setNumberB($numberB) {
$this->numberB = $numberB;
}
public function getResult() {
$result = 0;
return $result;
}
}
/**
* @desc 加法类
*/
class Add extends Operation {
public function getResult() {
$result = 0;
$result = $this->getNumberA() + $this->getNumberB();
return $result;
}
}
/**
* @desc 减法类
*/
class Sub extends Operation {
public function getResult() {
$result = 0;
$result = $this->getNumberA() - $this->getNumberB();
return $result;
}
}
/**
* @desc 乘法类
*/
class Mul extends Operation {
public function getResult() {
$result = 0;
$result = $this->getNumberA() * $this->getNumberB();
return $result;
}
}
/**
* @desc 除法类
*/
class Div extends Operation {
public function getResult() {
$result = 0;
if ($this->getNumberB() == 0) {
echo '除数不能为0';
die;
} else {
$result = $this->getNumberA() / $this->getNumberB();
}
return $result;
}
}
/**
* @desc 平方根类
*/
class Sqrt extends Operation {
public function getResult() {
$result = 0;
if ($this->getNumberA() < 0) {
echo '不能小于0';
die;
} else {
$result = sqrt($this->getNumberA());
}
return $result;
}
}
/**
* @desc 简单工厂运算类
*/
class OperationFactory {
public static function createOperate($operate) {
$oper = null;
switch ($operate) {
case '+':
$oper = new Add();
break;
case '-':
$oper = new Sub();
break;
case '*':
$oper = new Mul();
break;
case '/':
$oper = new Div();
break;
case 'sqrt':
$oper = new Sqrt();
break;
}
return $oper;
}
}
$oper = OperationFactory::createOperate('+');
$oper->setNumberA(10);
$oper->setNumberB(5);
$result = $oper->getResult();
echo $result;