您的位置:首页 > 编程语言 > PHP开发

php八大设计模式之策略模式

2017-03-28 20:30 477 查看
策略模式提供一个虚拟的整体,根据不同的要求(参数)提供不同的“零件”(调用不同的“零件”实现不同的结果)。

<?php
/**
* 策略模式
*    跟工厂模式差别不大,用到谁就去实例化谁。
*
* 工厂模式,着眼于得到对象,并操作对象。
* 策略模式,着重得到对象某方法的运行结果。
*/
//计算器接口。
interface Math{
public function calc($op1,$op2);
}
//乘法类。
class MathMul implements Math{
public function calc($op1,$op2){
return $op1*$op2;
}
}
//除法类。
class MathDiv implements Math{
public function calc($op1,$op2){
return $op1/$op2;
}
}
////加法类。
class MathAdd implements Math{
public function calc($op1,$op2){
return $op1+$op2;
}
}
////减法类。
class MathDel implements Math{
public function calc($op1,$op2){
return $op1-$op2;
}
}
//我们将这些类组装起来,形成一个对外的虚拟计算器。
class CMath{
protected $calc=null;
public function __construct($type){
$type="Math".$type;
$this->calc=new $type;
}
public function getNum($op1,$op2){
return $this->calc->calc($op1,$op2);
}
}
//模拟前台的运算符。
$arr=['Add','Del','Div','Mul'];
shuffle($arr);
$pop=array_pop($arr);
//根据运算符拿到计算结果。
$c=new CMath($pop);
echo $c->getNum($o=rand(1,100),$p=rand(1,100));
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: