public function calculate($expression) { $stack = array(); foreach ($expression as $part) { if (in_array($part, array('+', '-', '*', '/'))) { $b = array_pop($stack); $a = array_pop($stack); $operation = OperationFactory::createOperation($part); $result = $operation->calculate($a, $b); array_push($stack, $result); } else { array_push($stack, $part); } } return $stack[0]; }
/** * Adds operations to task * * @param string $operationCode * @param mixed $arguments * @return void */ public function addOperation($operationCode, $arguments = null) { $this->operationsList[] = $this->operationFactory->create($operationCode, $arguments); }
<?php define('ROOT_PATH', dirname(__FILE__)); require_once ROOT_PATH . '/../../Loader.php'; $opra = OperationFactory::createOperation('+'); $opra->setNumberA(11); $opra->setNumberB(33); echo $opra->getResult();
return $numberA / $numberB; } } //////////////////////////////////////////////////////////////// //简单运算工厂类 class OperationFactory { public static function createOperationObj($operation) { switch ($operation) { case '+': return new OperationAdd(); break; case '-': return new OperationSub(); break; case '*': return new OperationMul(); break; case '/': return new OperationDiv(); break; } } } ///////////////////////////////////////////////////////////////// //客户段代码 $operationObj = OperationFactory::createOperationObj('+'); $result = $operationObj->getResult(12, 13); var_dump($result); //25
/** * @inheritDoc */ public function collect($collection = null) { return $this->then($this->operations->collect(func_get_args())); }
public function testCreateUnknown() { $this->assertNull(OperationFactory::createOperation('')); }
<?php require_once './OperationFactory.php'; require_once './OperationMain.php'; $oper = OperationFactory::creatOperate($_POST['operator']); $oper->set_numberA($_POST['num1']); $oper->set_numberB($_POST['num2']); $result = $oper->get_result(); var_dump($result);
public function testCreateException() { $notRegisteredOperation = 'coffee'; $this->setExpectedException('Magento\\Tools\\Di\\App\\Task\\OperationException', sprintf('Unrecognized operation "%s"', $notRegisteredOperation), OperationException::UNAVAILABLE_OPERATION); $this->factory->create($notRegisteredOperation); }