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
  • 相关阅读:
    简单排序(冒泡、选择、插入)
    配置Tomcat数据源
    使用spring的邮件发送功能
    安装Tomcat
    Spring-MongoDB简单操作
    cisco ASA ios升级或恢复
    ASA 用TFTP 备份配置方法
    DELL MD3200i存储控制器解锁方法
    IBM ServerGuide引导盘全系列下载网址
    ASA5520远程配置 telnet,ssh
  • 原文地址:https://www.cnblogs.com/itsuibi/p/11058164.html
Copyright © 2011-2022 走看看