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));
  

  

posted @ 2020-07-23 22:06  coder_xds  阅读(132)  评论(0编辑  收藏  举报