策略模式提供一个虚拟的整体,根据不同的要求(参数)提供不同的“零件”(调用不同的“零件”实现不同的结果)。
<?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));
?>