<?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();
相关文章
- 10-28大话设计模式----中介者模式
- 10-28设计模式-迭代器模式
- 10-28设计模式-访问者模式
- 10-28设计模式之美学习-结构型-装饰者模式(二十)
- 10-28设计模式-状态模式
- 10-28大话设计模式之<一>计算器的深思
- 10-28设计模式(九)装饰模式
- 10-28设计模式---策略模式
- 10-28Head First之策略模式
- 10-28设计模式之策略模式