<?php /** * 狀態模式 * 容許一個實例在內部修改狀態行爲 * */ /** * Class state * 狀態類 抽象 */ abstract class AState { abstract function handle(Context $context); } /** * Class StateA * 抽象狀態實例A */ class StateA extends AState { // 保存自身實例 private static $_examples; private function __construct() { // echo '實例自動構造函數A' . PHP_EOL; } private function __clone() { // echo '實例自動析構函數A' . PHP_EOL; // TODO: Implement __clone() method. } public static function Examples() { // 獲取自身實例 if (!isset(self::$_examples)) { self::$_examples = new self; } return self::$_examples; } function Handle(Context $context) { // TODO: Implement handle() method. echo 'stateA' . PHP_EOL; $context->ChangeState(StateB::Examples()); } } /** * Class StateB * 抽象狀態B */ class StateB extends AState { // 保存自身實例 private static $_examples; private function __construct() { // echo '實例自動構造函數B' . PHP_EOL; } private function __clone() { // echo '實例自動析構函數B' . PHP_EOL; // TODO: Implement __clone() method. } public static function Examples() { // 獲取自身實例 if (!isset(self::$_examples)) { self::$_examples = new self; } return self::$_examples; } // Handle 狀態實例轉跳 function Handle(Context $context) { // TODO: Implement handle() method. echo 'stateB' . PHP_EOL; $context->ChangeState(StateA::Examples()); } } /** * Class context * 上下文,環境內容 * 狀態保存類 */ class Context { protected $state; public function __construct(AState $AState) { // 初始狀態 保存 $this->state = $AState; } // 修改狀態 public function ChangeState(AState $AState) { $this->state = $AState; } public function Handle() { // 調用保存實例的Handle $this->state->Handle($this); } public function Request() { $this->state->Handle($this); } } $context = new Context(StateB::Examples()); $context->Request(); // stateB $context->Request(); // stateA $context->Request(); // stateB