abstract class State {
public abstract function writeProgram($w);
}
//上午工作状态
class ForenoonState extends State {
public function writeProgram($w) {
if($w->hour < 12) {
echo '当前时间:'.$w->hour.'点 上午工作,精神百倍。<br/>';
} else {
$w->setState(new NoonState());
$w->writeProgram();
}
}
}
//中午工作状态
class NoonState extends State {
public function writeProgram($w) {
if($w->hour < 13) {
echo '当前时间:'.$w->hour.'点 饿了,午饭;犯困,午休。<br/>';
} else {
$w->setState(new AfternoonState());
$w->writeProgram();
}
}
}
//下午工作状态
class AfternoonState extends State {
public function writeProgram($w) {
if($w->hour < 17) {
echo '当前时间:'.$w->hour.'点 下午工作状态还不错,继续努力。<br/>';
} else {
$w->setState(new EveningState());
$w->writeProgram();
}
}
}
//晚间工作状态
class EveningState extends State {
public function writeProgram($w) {
if($w->taskFinished) {
$w->setState(new RestState());
$w->writeProgram();
} else {
if($w->hour < 21) {
echo '当前时间:'.$w->hour.'点 加班哦,疲劳至极。<br/>';
} else {
$w->setState(new SleepingState());
$w->writeProgram();
}
}
}
}
//睡眠状态
class SleepingState extends State {
public function writeProgram($w) {
echo '当前时间:'.$w->hour.'点 不行了,睡着了。<br/>';
}
}
//下班休息状态
class RestState extends State {
public function writeProgram($w) {
echo '当前时间:'.$w->hour.'点下班回家了。<br/>';
}
}
//工作
class Work {
private $current;
public function __set($key, $value) {
$this->$key = $value;
}
public function __get($key) {
if(isset($this->$key)) {
return $this->$key;
} else {
return NULL;
}
}
public function __construct() {
$this->current = new ForenoonState();
}
private $hour;
private $TaskFinished = false;
public function setState($s) {
$this->current = $s;
}
public function writeProgram() {
$this->current->writeProgram($this);
}
}
$emergencyProjects = new Work();
$emergencyProjects->hour = 9;
$emergencyProjects->writeProgram();
$emergencyProjects->hour = 10;
$emergencyProjects->writeProgram();
$emergencyProjects->hour = 12;
$emergencyProjects->writeProgram();
$emergencyProjects->hour = 13;
$emergencyProjects->writeProgram();
$emergencyProjects->hour = 14;
$emergencyProjects->writeProgram();
$emergencyProjects->hour = 17;
$emergencyProjects->writeProgram();
$emergencyProjects->taskFinished = false;
$emergencyProjects->hour = 19;
$emergencyProjects->writeProgram();
$emergencyProjects->hour = 22;
$emergencyProjects->writeProgram();
大话设计模式-状态模式
最新推荐文章于 2022-12-24 16:47:14 发布