PHP代码实现简单工厂模式
<?php
abstract class Operation
{
public $numberA = 0;
public $numberB = 0;
abstract public function getResult();
}
class OperationAdd extends Operation
{
public function getResult()
{
return $this->numberA + $this->numberB;
}
}
class OperationSub extends Operation
{
public function getResult()
{
return $this->numberA - $this->numberB;
}
}
class OperationMult extends Operation
{
public function getResult()
{
return $this->numberA * $this->numberB;
}
}
class OperationDiv extends Operation
{
public function getResult()
{
return $this->numberA / $this->numberB;
}
}
class OperationFactory
{
public function createOperation($option)
{
switch ($option) {
case '+':
$result = new OperationAdd();
break;
case '-':
$result = new OperationSub();
break;
case '*':
$result = new OperationMult();
break;
case '/':
$result = new OperationDiv();
break;
}
return $result;
}
}
$operationObject = (new OperationFactory())->createOperation('+');
$operationObject->numberA = 3;
$operationObject->numberB = 5;
var_dump($operationObject->getResult());