策略模式和工厂模式很像。
工厂模式:着眼于得到对象,并操作对象。
策略模式:着重得到对象某方法的运行结果。
示例:
//实现一个简单的计算器
interface MathOp{
public function calculation($num1,$num2);
}
//加法
class MathAdd implements MathOp{
public function calculation($num1,$num2){
return $num1 + $num2;
}
}
//减法
class MathSub implements MathOp{
public function calculation($num1,$num2){
return $num1 - $num2;
}
}
//乘法
class MathMulti implements MathOp{
public function calculation($num1,$num2){
return $num1 * $num2;
}
}
//除法
class MathDiv implements MathOp{
public function calculation($num1,$num2){
return $num1 / $num2;
}
}
class Op{
protected $op_class = null;
public function __construct($op_type){
$this->op_class = 'Math' . $op_type;
}
public function get_result($num1,$num2){
$cls = new $this->op_class;
return $cls->calculation($num1,$num2);
}
}
$obj = new Op('Add');
echo $obj->get_result(6,2);//8
$obj = new Op('Sub');
echo $obj->get_result(6,5);//1
$obj = new Op('Multi');
echo $obj->get_result(6,2);//12
$obj = new Op('Div');
echo $obj->get_result(6,2);//3
上一篇:php中策略模式的原理是什么
下一篇:如何在PHP项目中应用观察者模式