观察者模式
定义:Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
中文:在对象之间定义一个一对多的依赖,当一个对象状态改变的时候,所有依赖的对象都会自动收到通知。
现在都知道买房很苦逼,时刻关注房价,生怕错过一个亿。这个时候我们就要不管关注房价的变化情况。比如小绿和小红要买房(观察者) 房地产(被观察者)。
观察者对象
interface Observer
{
public function update($obj);
}
观察者实体
class PersonA implements Observer
{
function update($obj)
{
if ($obj->price == 10) {
echo '我要买10套'.PHP_EOL;
}
}
}
class PersonB implements Observer
{
public function update($obj)
{
if ($obj->price <= 5) {
echo '我要买1套';
}else{
echo '在等等,在等等 等等.......';
}
}
}
被观察者
class House
{
private $observers = [];
public function attach($ob)
{
$this->observers[] = $ob;
}
public function detach($ob)
{
$position = 0;
foreach ($this->observers as $item) {
if ($ob == $item) {
array_splice($this->observers, ($position), 1);
}
++$position;
}
}
public function notify($obj)
{
foreach ($this->observers as $ob) {
$ob->update($obj);
}
}
public function sale($param)
{
$obj = new stdClass();
$obj->message = $param['message'];
$obj->price = $param['price '];
$this->notify($obj);
}
}
从此小红和小绿每天都观察这个房子的价格~~~~~~等啊等 等啊等
突然
房地产降价了
$persona = new PersonA();
$personb= new PersonB();
$house = new House();
$house->attach($persona);
$house->attach($personb);
$house->sale(['message'=>'降价通知','price'=>10]);
这个时候小红和小绿都会收到响应的通知。 如果使用php 可以选择php自带spl 很方便实现观察者模式.
参考
SplSubject,观察者对象
SplObserver,观察者
SplObjectStorage,存储对象
class ConcreteSubject implements SplSubject
{
private $observers;
private $data;
public function setObservers()
{
$this->observers = new SplObjectStorage();
}
public function attach(SplObserver $observer)
{
$this->observers->attach($observer);
}
public function detach(SplObserver $observer)
{
$this->observers->detach($observer);
}
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function setData($dataNow)
{
$this->data = $dataNow;
}
public function getData()
{
return $this->data;
}
}
class ConcreteObserver implements SplObserver
{
public function update(SplSubject $subject)
{
echo $subject->getData() . PHP_EOL;
}
}
|