亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

PHP觀察者模式示例【Laravel框架中有用到】

 更新時間:2018年06月15日 12:09:42   作者:白小獅  
這篇文章主要介紹了PHP觀察者模式,結(jié)合實例形式分析了php觀察者模式的簡單定義與使用操作技巧,需要的朋友可以參考下

本文實例講述了PHP觀察者模式。分享給大家供大家參考,具體如下:

<?php
//觀察者模式
//抽象主題類
interface Subject
{
  public function attach(Observer $Observer);
  public function detach(Observer $observer);
  //通知所有注冊過的觀察者對象
  public function notifyObservers();
}
//具體主題角色
class ConcreteSubject implements Subject
{
  private $_observers;
  public function __construct()
  {
    $this->_observers = array();
  }
  //增加一個觀察者對象
  public function attach(Observer $observer)
  {
    return array_push($this->_observers,$observer);
  }
  //刪除一個已經(jīng)注冊過的觀察者對象
  public function detach(Observer $observer)
  {
    $index = array_search($observer,$this->_observers);
    if($index === false || !array_key_exists($index, $this->_observers)) return false;
    unset($this->_observers[$index]);
    return true;
  }
  //通知所有注冊過的觀察者
  public function notifyObservers()
  {
    if(!is_array($this->_observers)) return false;
    foreach($this->_observers as $observer)
    {
      $observer->update();
    }
    return true;
  }
}
//抽象觀察者角色
interface Observer
{
  //更新方法
  public function update();
}
//觀察者實現(xiàn)
class ConcreteObserver implements Observer
{
  private $_name;
  public function __construct($name)
  {
    $this->_name = $name;
  }
  //更新方法
  public function update()
  {
    echo 'Observer'.$this->_name.' has notify';
  }
}
$Subject = new ConcreteSubject();
//添加第一個觀察者
$observer1 = new ConcreteObserver('baixiaoshi');
$Subject->attach($observer1);
echo 'the first notify:';
$Subject->notifyObservers();
//添加第二個觀察者
$observer2 = new ConcreteObserver('hurong');
echo '<br/>second notify:';
$Subject->attach($observer2);
/*echo $Subject->notifyObservers();
echo '<br/>';
$Subject->notifyObservers();*/
?>

運(yùn)行結(jié)果:

the first notify:Observerbaixiaoshi has notify
second notify:

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家PHP程序設(shè)計有所幫助。

相關(guān)文章

最新評論