出现这种模式允许一个对象当其内部状态改变时来改变其行为对象看起来似乎修改了它所属的类
ConcreteStateB(具体状态B)
This subclass implements a behaviour associated with a state of the Context.
(这个子类实现了一个上下文状态相关的行为。)
ConcreteStateA(具体状态A)
This subclass implements a behaviour associated with a state of the Context.
(这个子类实现了一个上下文状态相关的行为。)
State(状态)
This class defines an interface for encapsulating the behaviour associated with a particular([pə'tikjulə] 特定的) state of the Context.
(这个类定义了一个接口用于封装一个上下文的特定状态相关联的行为。)
Context(上下文)
This class defines the interface of interest to clients and maintains an instance of a ConcreteState subclass that defines the current state.
(这个类定义了客户感兴趣的接口和维护一个定义了当前状态的ConcreteState子类的一个实例)
<?php
class StateA implements State
{
public function handle($context) {
$context->setState(new StateB());
}
public function display() {
echo "state A";
}
}
class StateB implements State
{
public function handle($context) {
$context->setState(new StateC());
}
public function display() {
echo "state B";
}
}
class StateC implements State
{
public function handle($context) {
$context->setState(new StateA());
}
public function display() {
echo "state C";
}
}
interface State
{
public function handle($state);
public function display();
}
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();
评论