class Program {
public $symbol;
public $num1;
public $num2;
public function __construct($symbol, $num1, $num2) {
$this->symbol = $symbol;
$this->num1 = $num1;
$this->num2 = $num2;
}
public function calculate() {
switch ($this->symbol) {
case '+':
$result = $this->num1 + $this->num2;
break;
case '-':
$result = $this->num1 - $this->num2;
break;
case '*':
$result = $this->num1 * $this->num2;
break;
case '/':
if ($this->num2 != 0) {
$result = $this->num1 / $this->num2;
} else {
$result = "除數不能爲0";
}
break;
default:
$result = "運算符錯誤";
}
return $result;
}
}
$program = new Program('+', 1, 14);
$result = $program->calculate();
print_r($result);//15
複製代碼
在上面的代碼中存在的缺點: 緊耦合,不易擴展,若是新增了一個平方根運算,卻須要讓加減乘除都來參與編譯,若是一不當心把加法運算改爲了減法,那就麻煩了。php
將加減乘除解耦,每個運算用單獨的類去寫,再用工廠模式實例化出合適的對象,經過多態返回計算器結果,後面若是再加一個平方根運算能夠新增一個平方根的類,若是須要修改加法運算,那就只須要修改OperationAdd類。this
class Operation {
public $num1;
public $num2;
}
class OperationAdd extends Operation {
public function getResult() {
$result = $this->num1 + $this->num2;
return $result;
}
}
class OperationSub extends Operation {
public function getResult() {
$result = $this->num1 - $this->num2;
return $result;
}
}
class OperationMul extends Operation {
public function getResult() {
$result = $this->num1 * $this->num2;
return $result;
}
}
class OperationDiv extends Operation {
public function getResult() {
if ($this->num2 != 0) {
$result = $this->num1 / $this->num2;
} else {
$result = "除數不能爲0";
}
return $result;
}
}
class OperationFactory {
public static function createOperate($symbol) {
switch ($symbol) {//多態
case '+':
$result = new OperationAdd();
break;
case '-':
$result = new OperationSub();
break;
case '*':
$result = new OperationMul();
break;
case '/':
$result = new OperationDiv();
break;
default:
$result = NULL;
}
return $result;
}
}
$operationFactory = OperationFactory::createOperate('+');
$operationFactory->num1 = 21;
$operationFactory->num2 = 11;
echo $operationFactory->getResult();//32
複製代碼