PHP设计模式之:工厂模式
<?php
abstract class Operation
{
public numA =
0;
public numB = 0;
public
function __construct($numA, $numB)
{
$this->numA = $numA;
$this->numB = $numB;
}
abstract function getResult();
}
class
OperationAdd extends Operation
{
public function
getResult()
{
return numA+numB;
}
}
class OperationSub
extends Operation
{
public function
getResult()
{
return numA - numB;
}
}
class OperationMul
extends Operation
{
public function
getResult()
{
return numA * numB;
}
}
class OperationDiv
extends Operation
{
public function
getResult()
{
if(numB == 0)
{
throw new Exception("除数不能为 0
。");
}
return (double) (numA / numB);
}
}
/** *************************************** */
//
简单运算工厂类
class OperationFactory
{
public static
createOperate($operation, $numA, $numB)
{
switch($operation)
{
case
‘+‘:
$oper = new OperationAdd($numA, $numB);
break;
case ‘-‘:
$oper = new
OperationSub($numA, $numB);
break;
case ‘*‘:
$oper = new
OperationMul($numA, $numB);
break;
case ‘/‘:
$oper = new
OperationDiv($numA, $numB);
break;
}
return
$oper;
}
}
/** ************************
*/
// 调用方式
$numA = 100;
$numB = 8;
$operation = ‘+‘;
$oper =
OperationFactory::createOperate($operation, $numA, $numB);
echo
$oper.getResult();
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。