<?php
#状态模式:当一个对象的内在状态改变时允许改变其行为,这个对象看起来就像是改变了其类。
//抽象状态
abstract class State{
public $w;
abstract function WriteProgram($w);
}
//上午和中午工作状态类
class ForenoonState extends State{
function WriteProgram($w){
if($w->Hour<12){
echo "当前时间:".$w->Hour ."点 上午工作,精神百倍";
}else{
$w->SetState(new NoonState());
$w->WriteProgram();
}
}
}
//中午工作状态
class NoonState extends State{
public function WriteProgram($w){
if($w->Hour<13){
echo "当前时间:".$w->Hour ."点 饿了,午饭;犯困,午休。";
}else{
$w->setState(new AfternoonState());
$w->WriteProgram();
}
}
}
//下午工作状态
class AfternoonState extends State{
public function WriteProgram($w){
if($w->Hour<17){
echo ‘当前时间:‘.$w->Hour ."点 下午状态还不错,继续努力";
}else{
$w->SetState(new EveningState());
$w->WiteProgram();
}
}
}
//晚间工作状态
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 ."点 加班哦,疲累之极";
}else{
$w->SetState(new SleepingState());
$w->WriteProgram();
}
}
}
}
//睡眠状态和下班休息状态
//睡眠状态
class SleepingState extends State
{
public function WriteProgram($w){
echo "当前时间:".$w->Hour."点不行了,睡着了";
}
}
//下班休息状态
class RestState extends State{
public function WriteProgram($w){
echo "当前时间:".$w->Hour ."点下班回家了";
}
}
//工作类
class Work{
private $current;
private $Hour;
private $finish = false;
public function __construct(){
$this->current = new ForenoonState();
}
public function __get($Hour){
return $this->$Hour;
}
public function __set($param,$val){
$this->$param = $val;
}
public function SetState($s){
$this->current = $s;
}
public function WriteProgram(){
$this->current->WriteProgram($this);
}
}
//客户端代码
//紧急项目
$work = new Work();
$work->Hour = 9;
$work->WriteProgram();
$work->Hour = 15;
$work->WriteProgram();
?>
大话设计模式之----状态模式,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/wendong/p/3848875.html