VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > PHP >
  • 【php设计模式】观察者模式

  当对象间存在一对多关系时,则使用观察者模式。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。

复制代码
<?php
class Subject{
    private $observer_list;
    private $num;

    public function __construct(){
        $this->observer_list = new SplDoublyLinkedList();
    }

    public function attach(Observer $observer){
        $this->observer_list->push($observer);
    }

    public function setNum($num){
        $this->num = $num;
        $this->notify();
    }

    public function getNum(){
        return $this->num;
    }

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

abstract class Observer{
    public $subj;
    public function __construct(Subject $subj){
        $this->subj = $subj;
        $this->subj->attach($this);
    }

    abstract function update();
}

class BinObserver extends Observer{
    public function update(){
        echo "二进制更新:".decbin($this->subj->getNum())."\n";
    }
}

class OctObserver extends Observer{
    public function update(){
        echo "八进制更新:".decoct($this->subj->getNum())."\n";
    }
}

class HexObserver extends Observer{
    public function update(){
        echo "十六进制更新:".dechex($this->subj->getNum())."\n";
    }
}

$subject = new Subject();
new BinObserver($subject);
new OctObserver($subject);
new HexObserver($subject);
$subject->setNum(22);
复制代码

运行结果:

二进制更新:10110
八进制更新:26
十六进制更新:16

 


相关教程