状态模式
状态模式:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类当中,可以把复杂的判断逻辑简化。(当类中的方法含有多个判断时使用如果状态判断很简单那就没必要用状态模式了)
abstract class State
{
public abstract function Handle($context);
}
class ConcreteStateA extends State
{
public function Handle($context)
{
$context->State = new ConcreteStateB();
}
}
class ConcreteStateB extends State
{
public function Handle($context)
{
$context->satate = new ConcreteStateA();
}
}
class Context
{
private $state;
public function __construct($state)
{
$this->state = $state;
}
public function Request(){
$this->state->Handle($this);
}
}
$state = new ConcreteStateA();
$context = new Context($state);
$context->Request();
-----------------------------------------------------------
abstract class State
{
public abstract function Coding($work);
}
class ForenoonState extends State
{
public function Coding($work)
{
if($work->hour<12){
echo '当前时间'.$work->hour.'点上午工作,精神百倍<br>';
}else{
$work->setState(new NoonState());
$work->Coding();
}
}
}
class NoonState extends State
{
public function Coding($work)
{
if ($work->hour<13){
echo '当前时间'.$work->hour.'点饿了,午饭:犯困,午休<br>';
}else{
$work->setState(new AfternoonState());
$work->Coding();
}
}
}
class AfternoonState extends State
{
public function Coding($work)
{
if($work->hour < 17){
echo '当前时间'.$work->hour.'点饿了,午饭:犯困,午休<br>';
}else{
$work->setState(new EveningState());
$work->Coding();
}
}
}
class EveningState extends State
{
public function Coding($work)
{
if($work->finished){
$work->setState(new RestState());
$work->Coding();
}else{
if($work->hour < 21){
echo '当前时间'.$work->hour.'点饿了,加班哦,疲累之极<br>';
}else{
$work->setState(new SleepingState());
$work->Coding();
}
}
}
}
class SleepingState extends State
{
public function Coding($work)
{
echo '当前时间'.$work->hour.'睡着了<br>';
}
}
class RestState extends State
{
public function Coding($work)
{
echo '当前时间'.$work->hour.'下班回家了<br>';
}
}
class Work
{
private $state;
public $hour;
public $finished;
public function __construct()
{
$this->state = new ForenoonState();
}
public function setState($state){
$this->state = $state;
}
public function coding(){
$this->state->coding($this);
}
}
$work = new Work();
$work->hour = 9;
$work->coding();
$work->hour = 10;
$work->coding();
$work->hour = 12;
$work->coding();
$work->hour = 13;
$work->coding();
$work->hour = 14;
$work->coding();
$work->hour = 17;
$work->coding();