zoukankan      html  css  js  c++  java
  • 【php设计模式】观察者模式

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

    <?php
    interface Subject{
        public function attach(Observer $observer);
        public function detach(Observer $observer);
        public function notify();
    }
    
    class SubjectItem implements Subject{
        private $observer_list;
        private $num;
    
        public function __construct(){
            $this->observer_list = new SplObjectStorage;
        }
    
        public function attach(Observer $observer){
            $this->observer_list->attach($observer);
        }
    
        public function detach(Observer $observer){
            $this->observer_list->detach($observer);
        }
    
        public function setNum($num){
            $this->num = $num;
            $this->notify();
        }
    
        public function getNum(){
            return $this->num;
        }
    
        public function notify(){
            for($this->observer_list->rewind();$this->observer_list->valid();$this->observer_list->next()){
                $this->observer_list->current()->update($this);
            }
    
        }
    }
    
    abstract class Observer{
        abstract function update(Subject $subject);
    }
    
    class BinObserver extends Observer{
        public function update(Subject $subject){
            echo "二进制更新:".decbin($subject->getNum())."
    ";
        }
    }
    
    class OctObserver extends Observer{
        public function update(Subject $subject){
            echo "八进制更新:".decoct($subject->getNum())."
    ";
        }
    }
    
    class HexObserver extends Observer{
        public function update(Subject $subject){
            echo "十六进制更新:".dechex($subject->getNum())."
    ";
        }
    }
    
    $subject = new SubjectItem();
    $subject->attach(new BinObserver());
    $subject->attach(new OctObserver());
    $subject->attach(new HexObserver());
    $subject->setNum(22);

    运行结果:

    二进制更新:10110
    八进制更新:26
    十六进制更新:16
  • 相关阅读:
    CentOS 安装 Xamarin官方Mono
    mongo命令行下去除重复的数据
    通过前端js将页面表格导出为PDF(二)
    通过前端js将页面表格导出为PDF(一)
    ubuntu下手动安装MongoDB
    在django项目下执行定时任务
    django+uwsgi+nginx部署在ubuntu系统上
    Nginx(三)
    Nginx(二)
    Nginx(一)
  • 原文地址:https://www.cnblogs.com/itsuibi/p/11058164.html
Copyright © 2011-2022 走看看