开发中,有些验证功能需要我们实现,类似于这类功能,我们往往可以通过观察者模式去实现。下面分析下观察者模式。
- 遵循单一职责原则
- 对于不同的验证,可以向外扩展,无需修改内部结构。
- 符合观察者与被观察者的模式
<?php
class user implements SplSubject
{
public $lognum;
public $hobby;
protected $observers = null;
public function __construct($hobby)
{
$this->lognum = rand(1, 10);
$this->hobby = $hobby;
$this->observers = new SplObjectStorage();
}
public function login()
{
$this->notify();
}
//添加观察者服务
public function attach(SplObserver $observer)
{
$this->observers->attach($observer);
}
//删除观察者服务
public function detach(SplObserver $observer)
{
$this->observers->detach($observer);
}
//触发观察者服务
public function notify()
{
//循环观察者服务
$this->observers->rewind();
while ($this->observers->valid()) {
$observer = $this->observers->current();
$observer->update($this);
$this->observers->next();//改变指针
}
}
}
//创建观察者
class serity implements SplObserver
{
public function update(SplSubject $subject)
{
if ($subject->lognum < 5) {
echo '这是第' . $subject->lognum . "次登陆<br>";
} else {
echo '这是第' . $subject->lognum . '次登陆,异常<br>';
}
}
}
class ad implements SplObserver
{
public function update(SplSubject $subject)
{
if ($subject->hobby == 'sports') {
echo "足球赛门票预订<br>";
} else {
echo '学习时间到了....';
}
}
}
//实施观察
$user = new user('study');
$user->attach(new serity());
$user->attach(new ad);
$user->login();