狀態模式能夠基於一個對象的同種事務而封裝出不一樣的行爲。它提供一種簡潔的方式使得對象在運行時能夠改變自身行爲,而沒必要藉助單一龐大的條件判斷語句。php
<?php namespace DesignPatterns\Behavioral\State; class ContextOrder extends StateOrder { public function getState():StateOrder { return static::$state; } public function setState(StateOrder $state) { static::$state = $state; } public function done() { static::$state->done(); } public function getStatus(): string { return static::$state->getStatus(); } }
<?php namespace DesignPatterns\Behavioral\State; abstract class StateOrder { /** * @var array */ private $details; /** * @var StateOrder $state */ protected static $state; /** * @return mixed */ abstract protected function done(); protected function setStatus(string $status) { $this->details['status'] = $status; $this->details['updatedTime'] = time(); } protected function getStatus(): string { return $this->details['status']; } }
<?php namespace DesignPatterns\Behavioral\State; class ShippingOrder extends StateOrder { public function __construct() { $this->setStatus('shipping'); } protected function done() { $this->setStatus('completed'); } }
<?php namespace DesignPatterns\Behavioral\State; class CreateOrder extends StateOrder { public function __construct() { $this->setStatus('created'); } protected function done() { static::$state = new ShippingOrder(); } }
<?php namespace DesignPatterns\Behavioral\State\Tests; use DesignPatterns\Behavioral\State\ContextOrder; use DesignPatterns\Behavioral\State\CreateOrder; use DesignPatterns\Behavioral\State\ShippingOrder; use PHPUnit\Framework\TestCase; class StateTest extends TestCase { public function testCanShipCreatedOrder() { $order = new CreateOrder(); $contextOrder = new ContextOrder(); $contextOrder->setState($order); $contextOrder->done(); $this->assertEquals('shipping', $contextOrder->getStatus()); } public function testCanCompleteShippedOrder() { $order = new ShippingOrder(); $contextOrder = new ContextOrder(); $contextOrder->setState($order); $contextOrder->done(); $this->assertEquals('completed', $contextOrder->getStatus()); } }
PHP 互聯網架構師 50K 成長指南+行業問題解決總綱(持續更新)sql
面試10家公司,收穫9個offer,2020年PHP 面試問題shell
★若是喜歡個人文章,想與更多資深開發者一塊兒交流學習的話,獲取更多大廠面試相關技術諮詢和指導,歡迎加入咱們的羣啊,暗號:phpzh(君羊號碼856460874)。設計模式
內容不錯的話但願你們支持鼓勵下點個贊/喜歡,歡迎一塊兒來交流;另外若是有什麼問題 建議 想看的內容能夠在評論提出架構