状态模式
状态模式:允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。
在很多情况下,一个对象的行为取决于一个或多个动态变化的属性,这样的属性叫做状态,这样的对象叫做有状态的(stateful)对象,这样的对象状态是从事先定义好的一系列值中取出的。当一个这样的对象与外部事件产生互动时,其内部状态就会改变,从而使得系统的行为也随之发生变化。
类结构图:

php代码示例:
<?php
class State{
function WriteProgram(){
}
}
class Work{
public $hour,$current;
function __construct(){
$this -> hour = 9;
$this -> current = new ForenoonState();
}
function SetState($temp){
$this -> current = $temp;
}
function WriteProgram(){
$this -> current -> WriteProgram($this);
}
}
class NoonState extends State{
function WriteProgram($w){
print "noon working\n";
if($w -> hour < 13){
print "fun.\n";
}else{
print "need to rest\n";
}
}
}
class ForenoonState extends State{
function WriteProgram($w){
if($w -> hour < 12){
print "morning working\n";
}else{
$w -> SetState(new NoonState());
$w -> WriteProgram();
}
}
}
$mywork = new Work();
$mywork -> hour = 9;
$mywork -> WriteProgram();
$mywork -> hour = 14;
$mywork -> WriteProgram();
?>

浙公网安备 33010602011771号