- 什么是状态设计模式
状态设计模式的作用是允许对象在状态改变时,改变其行为。如游戏中经常用到状态设计模式,因为游戏中的对象往往会非常频繁的改变状态 - 何时使用状态设计模式
一个对象依赖于它的状态时,它肯定会频繁的改变,这种情况下,有状态设计模式既有绝对的优势
下面的示例代码是利用状态设计模式实现电灯的开灯和关灯。
<?php
class Context {
private $offState;
private $onState;
private $currentstate;
public function __construct() {
$this->offState = new OffState($this);
$this->onState = new OnState($this);
$this->currentstate = $this->offState;
}
public function turnOnLight() {
$this->currentstate->turnLightOn();
}
public function turnOffLight() {
$this->currentstate->turnLightOff();
}
public function setState(IState $state) {
$this->currentstate = $state;
}
public function getOnState() {
return $this->onState;
}
public function getOffState() {
return $this->offState;
}
}
interface IState {
public function turnLightOn();
public function turnLightOff();
}
class OnState implements IState {
private $context;
function __construct(Context $context) {
$this->context = $context;
}
public function turnLightOn() {
echo "the light is already on->take no action<br>";
}
public function turnLightOff() {
echo "Lights Off!!<br />";
$this->context->setState($this->context->getOffState());
}
}
class OffState implements IState {
private $context;
function __construct(Context $context) {
$this->context = $context;
}
public function turnLightOn() {
echo "Lights On!!<br />";
$this->context->setState($this->context->getOnState());
}
public function turnLightOff() {
echo "the light is already off->take no action<br>";
}
}
class client {
private $context;
public function __construct() {
$this->context = new Context();//context对象作为一个参与者,来跟踪状态对象所处的状态
$this->context->turnOffLight();
$this->context->turnOnLight();
$this->context->turnOnLight();
$this->context->turnOffLight();
$this->context->turnOffLight();
}
}
new client();
the light is already off->take no action
Lights On!!
the light is already on->take no action
Lights Off!!
the light is already off->take no action
- 总结
状态设计模式是模拟器和游戏的主要方法,其实不局限与此,只要php程序的用户会用到一组有限的状态,开发人员就可以使用状态设计模式