1. 程式人生 > 實用技巧 >php設計模式-策略模式

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