策略模式是把算法,封裝起來。使得使用算法和使用算法環境分離開來,當算法發生改變時,咱們之須要修改客戶端調用算法,和增長一個新的算法封裝類。好比超市收銀,收營員判斷顧客是不是會員,當顧客不是會員時候,按照原價收取顧客購買商品費用,當顧客是會員的時候,滿100減5元。php
Cashier.phpgit
<?php namespace App\Creational\Strategy; class Cashier { private $cutomer; public function setStrategy(CustomerAbstract $customer) { $this->cutomer = $customer; } public function getMoney($price) { return $this->cutomer->pay($price); } }
CustomerAbstract.phpgithub
<?php namespace App\Creational\Strategy; abstract class CustomerAbstract { abstract public function pay($price); }
<?php namespace App\Creational\Strategy; class NormalCustomer extends CustomerAbstract { public function pay($price) { return $price; } }
<?php namespace App\Creational\Strategy; class VipCustomer extends CustomerAbstract { public function pay($price) { return $price - floor($price/100)*5; } }
測試代碼
StrategyTest.php測試
<?php /** * 策略模式 * Class StrategyTest */ class StrategyTest extends \PHPUnit\Framework\TestCase { public function testCustomer() { $price = 100; $vipCutomer = new \App\Creational\Strategy\VipCustomer(); $normalCustomer = new \App\Creational\Strategy\NormalCustomer(); $cashier = new \App\Creational\Strategy\Cashier(); $cashier->setStrategy($vipCutomer); $this->assertEquals(95, $cashier->getMoney($price)); $cashier->setStrategy($normalCustomer); $this->assertEquals(100, $cashier->getMoney($price)); } }