ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 示例 ### 概念示例 <details> <summary>main.php</summary> ``` <?php class Context { /** * @var State 引用的当前状态上下文 */ private $state; public function __construct(State $state) { $this->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(); ``` </details> <br /> 输出 ``` 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. ```