<?php
//接口
interface calc2
{
public function getValue($num1,$num2);
}
//加法,实现接口
class addStrategy implements calc2
{
public function getValue($num1, $num2)
{
return $num1 + $num2;
}
}
//减法
class subStrategy implements calc2
{
public function getValue($num1, $num2)
{
return $num1 - $num2;
}
}
//乘法
class mulStrategy implements calc2
{
public function getValue($num1, $num2)
{
return $num1 * $num2;
}
}
//除法
class divStrategy implements calc2
{
public function getValue($num1, $num2)
{
try
{
if(num2 == 0)
{
throw new Exception('chu shu bu neng wei 0');
}
else
{
return $num1 / $num2;
}
}
catch (Exception $e)
{
echo 'error :'.$e->getMessage();
}
}
}
//业务类
class calcContext
{
//私有变量,保存策略类实例
private $_strategy = null;
//构造函数,参数为策略类
public function __construct(calc2 $select)
{
$this->_strategy = $select;
}
//方法,设置策略类
public function setCalc(calc2 $select)
{
return $this->_strategy = $select;
}
//返回值,根据加载的策略类不同,动态调用接口方法
public function calcResult($num1,$num2)
{
return $this->_strategy->getValue($num1,$num2);
}
}
$r = new calcContext(new addStrategy());
echo $r->calcResult(100,99);
echo "<br>";
$r->setCalc(new mulStrategy());
echo $r->calcResult(100,99);