<?php /** * 状态模式 * 允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它所属的类 */ /*接口*/ interface State { public function handle($state);//切换到下一个状态 public function display();//显示当前状态 } /*状态A*/ class StateA implements State { public function handle($context) { $context->setState(new StateB()); } public function display() { echo "state A<br />"; } } /*状态B*/ class StateB implements State { public function handle($context) { $context->setState(new StateC()); } public function display() { echo "state B<br/>"; } } /*状态C*/ class StateC implements State { public function handle($context) { $context->setState(new StateA()); } public function display() { echo "state C<br/>"; } } class Context { private $_state = null; public function __construct($state)//给初始状态 { $this->setState($state); } public function setState($state)//设置状态的函数 { $this->_state = $state; } public function request()//执行显示状态并切换状态 { $this->_state->display(); $this->_state->handle($this); } } // 实例化一下 $objContext = new Context(new StateB()); $objContext->request(); $objContext->request(); $objContext->request(); $objContext->request(); $objContext->request(); ?>
时间: 2024-09-29 03:18:29