php 示例
最后更新于:2022-04-02 04:21:21
[TOC]
## 示例
### 概念示例
输出 ``` Context: Transition to RefactoringGuru\State\Conceptual\ConcreteStateA. ConcreteStateA handles request1. ConcreteStateA wants to change the state of the context. Context: Transition to RefactoringGuru\State\Conceptual\ConcreteStateB. ConcreteStateB handles request2. ConcreteStateB wants to change the state of the context. Context: Transition to RefactoringGuru\State\Conceptual\ConcreteStateA. ```
';
main.php
``` transitionTo($state); } /** * @param State $state */ public function transitionTo(State $state): void { echo "Context: Transition to " . get_class($state) . ".\n"; $this->state = $state; $this->state->setContext($this); } /** * 上下文代表其行为对象的当前状态的一部分 */ public function request1(): void { $this->state->handle1(); } public function request2(): void { $this->state->handle2(); } } abstract class State { /** * @var Context */ protected $context; public function setContext(Context $context) { $this->context = $context; } abstract public function handle1(): void; abstract public function handle2(): void; } class ConcreteStateA extends State { public function handle1(): void { echo "ConcreteStateA handles request1.\n"; echo "ConcreteStateA wants to change the state of the context.\n"; $this->context->transitionTo(new ConcreteStateB()); } public function handle2(): void { echo "ConcreteStateA handles request2.\n"; } } class ConcreteStateB extends State { public function handle1(): void { echo "ConcreteStateB handles request1.\n"; } public function handle2(): void { echo "ConcreteStateB handles request2.\n"; echo "ConcreteStateB wants to change the state of the context.\n"; $this->context->transitionTo(new ConcreteStateA()); } } /** * The client code. */ $context = new Context(new ConcreteStateB()); $context->request1(); $context->request2(); ```输出 ``` Context: Transition to RefactoringGuru\State\Conceptual\ConcreteStateA. ConcreteStateA handles request1. ConcreteStateA wants to change the state of the context. Context: Transition to RefactoringGuru\State\Conceptual\ConcreteStateB. ConcreteStateB handles request2. ConcreteStateB wants to change the state of the context. Context: Transition to RefactoringGuru\State\Conceptual\ConcreteStateA. ```