作业三:观察者模式在一个简单存钱demo中的应用

一、观察者模式得定义:

  观察者模式又称为订阅—发布模式,在此模式中,一个目标对象管理所有相依于它的观察者对象,并且在它本身的状态改变时主动发出通知。这通常透过呼叫各观察者所提供的方法来实现。此种模式通常被用来事件处理系统

二、观察者模式得结构:

  首先看下观察者模式的类图描述

三、代码实例

本次我们引用一个存储账户得简单demo来介绍一下观察者模式

class User implements \SplSubject{
  protected $storage;
  protected $name;
  public function __construct(\SplObjectStorage $storage){
    $this->storage = $storage;
  }
  public function add($name){
    $this->name = $name;
    $this->notify();
  }
  public function getName(){
    return $this->name;
  }
  public function attach(\SplObserver $observer){
    $this->storage->attach($observer);
  }
  public function detach(\SplObserver $observer){
    $this->storage->detach($observer);
  }

首先创建观察者(user):

class User implements \SplSubject{
  protected $storage;
  protected $name;
  public function __construct(\SplObjectStorage $storage){
    $this->storage = $storage;
  }

其次能够增加观察者:

public function add($name){
    $this->name = $name;
    $this->notify();
  }

并且也能够查询观察者得名字(并进行通知):

public function add($name){
    $this->name = $name;
    $this->notify();
  }

然后就是钱数得增加和减少得变动:

 public function attach(\SplObserver $observer){
    $this->storage->attach($observer);
  }
  public function detach(\SplObserver $observer){
    $this->storage->detach($observer);
  }

通知订阅者:

public function notify(){
    foreach ($this->storage as $observer) {
      $observer->update($this);
    }
  }

随后就是被观察者创建具体对象并实现:

class logger implements \SplObserver{
  public function update(\SplSubject $subject){
    printf('Log: Usuario %s creado %s'.PHP_EOL, $subject->getName(), date('H:i:s'));
  }
}
$user = new User(new \SplObjectStorage());
$user->attach(new logger());

四、总结(观察者模式得优点):

(1)抽象主题只依赖于抽象观察者
(2)观察者模式支持广播通信
(3)观察者模式使信息产生层和响应层分离

猜你喜欢

转载自www.cnblogs.com/zhongweics/p/9833631.html
今日推荐