Home >php教程 >php手册 >php设计模式 State (状态模式)

php设计模式 State (状态模式)

WBOY
WBOYOriginal
2016-06-21 08:54:141658browse

复制代码 代码如下:


/**
* 状态模式
*
* 允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它所属的类
*
*/
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);
}
}
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
";
}
}
// 实例化一下
$objContext = new Context(new StateB());
$objContext->request();
$objContext->request();
$objContext->request();
$objContext->request();
$objContext->request();



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn