• 观察者模式


    观察者模式是一种行为设计模式,允许你定义一种订阅机制,可在对象(A对象)事件发生时通知多个 ‘观察者’,即观察A对象的其他对象。

    代码示例

    注:PHP 中包含几个内置接口 SplSubject SplObserver 它们能让你的观察器模式实现与其他 PHP 代码兼容

    <?php
    
    class subject implements SplSubject
    {
        public $state;
    
        //存储订阅者,通知时候遍历使用
        private $observers;
    
        public function __construct()
        {
            $this->observers = new SplObjectStorage();
        }
    
        //添加订阅对象
        public function attach(SplObserver $observer)
        {
            // TODO: Implement attach() method.
            $this->observers->attach($observer);
        }
        
        //删除订阅对象
        public function detach(SplObserver $observer)
        {
            // TODO: Implement detach() method.
            $this->observers->detach($observer);
        }
        
        //遍历通知订阅者
        public function notify()
        {
            // TODO: Implement notify() method.
            foreach ($this->observers as $observer){
                $observer->update($this);
            }
        }
        
        //业务逻辑,业务变更时通知关联业务作出对应变更
        public function someBusinessLogic()
        {
            //模仿业务变更
            $this->state = mt_rand(0,10);
            
            //通知订阅者
            $this->notify();
        }
    }
    
    //订阅者A
    class  concreateObserverA implements SplObserver
    {
        public function update(SplSubject $subject)
        {
            // TODO: Implement update() method.
            echo 'A 关联业务变更';
        }
    }
    
    //订阅者B
    class  concreateObserverB implements SplObserver
    {
        public function update(SplSubject $subject)
        {
            // TODO: Implement update() method.
            echo 'B 关联业务变更';
        }
    }
    
    //客户端
    $subject = new subject();
    
    $conA = new concreateObserverA();
    //添加订阅者A
    $subject->attach($conA);
    
    $conB = new concreateObserverB();
    //添加订阅者B
    $subject->attach($conB);
    
    //业务逻辑变更后,通知订阅者使订阅者逻辑变更
    $subject->someBusinessLogic();
  • 相关阅读:
    operator模块和functools模块
    函数注解
    用户定义的可调用类型、从定位参数到仅限关键字参数
    可调用对象
    nxos启动的初始化和https访问nx-api
    网络安全基础之网络协议与安全威胁
    华为AC中服务集命令解释配置
    转:图解ARP协议(四)代理ARP原理与实践(“善意的欺骗”)
    windows下python3 python2 共存下安装virtualenvwrapper
    关于网络安全学习的网站
  • 原文地址:https://www.cnblogs.com/suojian/p/14023448.html
Copyright © 2020-2023  润新知