zl程序教程

您现在的位置是:首页 >  后端

当前栏目

php策略模式

PHP模式 策略
2023-09-11 14:22:41 时间

php策略模式


 

策略模式和工厂模式很像。

工厂模式:着眼于得到对象,并操作对象。
策略模式:着重得到对象某方法的运行结果。


 

示例:

//实现一个简单的计算器

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