php设计模式-策略模式

使用情景:if,else判断太短,优化代码的可读性。

interface Math
{
    public function calculate($a, $b);
}

class Calculator
{
    private $_operation;

    public function __construct($type)
    {
        $this->_operation = new $type;
    }

    public function calculate($a, $b)
    {
        return $this->_operation->calculate($a, $b);
    }
}

class Add implements Math
{
    public function calculate($a, $b)
    {
        return $a + $b;
    }
}

class Sub  implements Math
{
    public function calculate($a, $b)
    {
        return $a - $b;
    }
}


class Mult implements Math
{
    public function calculate($a, $b)
    {
        return $a * $b;
    }
}

class Div implements Math
{
    public function calculate($a, $b)
    {
        return $a / $b;
    }
}

$oprations = ['Add', 'Sub', 'Mult', 'Div'];
$a = rand(0,100);
$b = rand(0,100);
$calculator = new Calculator($oprations[ceil(rand(0, 3))]);
var_dump($calculator->calculate($a, $b));
  

  

原文地址:https://www.cnblogs.com/xiangdongsheng/p/13369095.html