B4:策略模式 Strategy

它定义了算法家族,分别封装起来,让他们之间可互相替换,此模式让算法的变化,不会影响到使用算法的客户.

UML

示例代码:

abstract class Strategy
{
    protected $money;

    public function __construct($money)
    {
        $this->money = $money;
    }

    abstract public function calcMoney();

    public function getMoney()
    {
        return $this->money;
    }
}

// 正常
class MoneyNomarl extends Strategy
{
    public function calcMoney()
    {
        return $this->money;
    }
}

// 返利
class MoneyRebate extends Strategy
{
    public function calcMoney()
    {
        return $this->money + $this->getRebate();
    }

    protected function getRebate()
    {
        return (int) $this->money * 0.1;
    }
}

class StrategyContext
{
    private $strategy;

    public function set(Strategy $strategy)
    {
        $this->strategy = $strategy;
    }

    public function getMoney()
    {
        return $this->strategy->calcMoney();
    }
}

$money = 100;
$strategy = new StrategyContext();
$strategy->set(new MoneyNomarl($money));
echo $strategy->getMoney();

  

原文地址:https://www.cnblogs.com/itfenqing/p/7788787.html