github地址:https://github.com/ZQCard/design_pattern
/** * 在状态模式(State Pattern)中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。 * 在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。 * 对象的行为依赖于它的状态(属性),并且可以根据它的状态改变而改变它的相关行为。 */
(1)State.class.php(接口,规定实现方法)
<?phpnamespace State;interface State{ ???public function doAction(Context $context);}
(2)Context.class.php (带有某个状态的类)
<?phpnamespace State;class Context{ ???private $state; ???public function __construct() ???{ ???????$this->state = null; ???} ???public function setState(State $state) ???{ ???????$this->state = $state; ???} ???public function getState() ???{ ???????return $this->state; ???}}
(3)StartState.class.php(具体的开始状态类)
<?phpnamespace State;class Context{ ???private $state; ???public function __construct() ???{ ???????$this->state = null; ???} ???public function setState(State $state) ???{ ???????$this->state = $state; ???} ???public function getState() ???{ ???????return $this->state; ???}}
(4)StopState.class.php(具体的结束状态类)
<?phpnamespace State;class StopState implements State{ ???public function doAction(Context $context) ???{ ???????echo "Player is in stop state"; ???????$context->setState($this); ???} ???public function handle() ???{ ???????return ‘stop state‘; ???}}
(5)state.php(客户端类)
<?phpspl_autoload_register(function ($className){ ???$className = str_replace(‘\\‘,‘/‘,$className); ???include $className.".class.php";});use State\Context;use State\StartState;use State\StopState;$context = new ?Context();$startState = new StartState();$startState->doAction($context);$context->getState()->handle();$startState = new StopState();$startState->doAction($context);$context->getState()->handle();
设计模式之状态模式(PHP实现)
原文地址:https://www.cnblogs.com/zhouqi666/p/9164932.html