设计模式之观察者模式&&状态模式
<?php interface Subject { function attach($obj); function detach($name); function notify(); } class Teacher implements Subject { private $attachArr = array(); function __construct() { } function attach($obj) { array_push($this->attachArr, $obj); } function detach($name) { unset($name); } function notify() { foreach($this->attachArr as $obj) { $obj->work(); } } function setStatus($status) { $this->status = $status; } }
interface Observe {
function work();
}
class Student implements Observe { function __construct($name, $work, $subjectObj) { $this->name = $name; $this->subjectObj = $subjectObj; $this->work = $work; } function work() { echo $this->subjectObj->status . "\n" .$this->name . $this->work . " \n"; } } $teacher = new Teacher(); $student1 = new Student('joey', 'paly table tenice', $teacher); $student2 = new Student('jam', 'sleeping', $teacher); $teacher->attach($student1); $teacher->attach($student2); $teacher->setStatus("quitting time \n"); $teacher->notify();
以上代码为观察者模式
观察者模式为当一个对象的状态改变的时候,其他的关联对象也做出相应。
观察者模式缺点:每个观察者对象必须继承这个抽像出来的接口类(比如这里的work),这样就造成了一些不方便,
可以通过委托实现。
<?php //状态模式 abstract class State { abstract function writeProgram(Work $work); } class ForenoonState extends State { function writeProgram(Work $work) { if ($work->hour < 12) { echo '当前时间是上午' . $work->hour . '工作精神百倍噢'; } else { $work->setState(new NoonState()); $work->writeProgram(); } } } class NoonState extends State { function writeProgram(Work $work) { if ($work->hour < 13 && $work->hour >= 12) { echo '当前时间是' . $work->hour . '午饭时间有点饿'; } else { $work->setState( new AfternoonState()); $work->writeProgram(); } } } class AfternoonState extends State { function writeProgram(Work $work) { if ($work->hour > 13 && $work->hour < 17) { echo '当前时间是' . $work->hour . '状态不错继续努力'; } else { $work->setState(new EveningState()); $work->writeProgram(); } } } class EveningState extends State { function writeProgram(Work $work) { if ($work->finish) { $work->setState(new RestState()); $work->writeProgram(); } else { if ($work->hour < 21) { echo '当前时间是' . $work->hour . '加班悲剧了'; } } } } class RestState extends State { function writeProgram(Work $work) { echo '当前时间是' . $work->hour . '下班回家了'; } } class Work { private $state; public $hour; public $finish = false; function __construct() { $this->state = new ForenoonState(); } function setState($state) { $this->state = $state; } function taskFinished() { $this->finish = true; } function writeProgram() { $this->state->writeProgram($this); } } $task = new Work(); $task->hour = 8; $task->writeProgram(); $task->hour = 12; $task->writeProgram(); $task->hour = 15; $task->writeProgram(); $task->hour = 20; $task->taskFinished(); $task->writeProgram();
状态模式适应于当判断逻辑太长的时候,当有新的状态添加不用修改原来的状态的代码。