1.赋值
abstract class Operation {
protected $number_a = 0;
protected $number_b = 0;
public function numberA($a) {
$this->number_a = $a;
}
public function numberB($b) {
$this->number_b = $b;
}
abstract function result();
}
2.运算
class Add extends Operation{
public function result()
{
return $this->number_a + $this->number_b;
}
}
class Sub extends Operation{
public function result()
{
return $this->number_a - $this->number_b;
}
}
class Mul extends Operation{
public function result()
{
return $this->number_a * $this->number_b;
}
}
3,工厂
class OperationFactory {
public function createOperate($operate) {
switch ($operate) {
case '+':
$result = new Add();
break;
case '-':
$result = new Sub();
break;
case '*':
$result = new Mul();
break;
default:
throw new \InvalidArgumentException('暂不支持的运算');
}
return $result;
}
}
4,执行
include_once "Operation.php";
include_once "OperationClass.php";
include_once "OperationFactory.php";
class Client
{
public function test() {
$oper_obj = new OperationFactory();
$op = $oper_obj->createOperate('-');
$op->numberA(1);
$op->numberB(2);
$res
= $op->result();
echo $res;
}
}
$Client = new Client();
$Client->test();