zoukankan      html  css  js  c++  java
  • 观察者模式

    <?php
    
    
    //=======观察者模式========
    //php5中提供了 观察者 和被观察者的接口
    //登录
    //实现观察者接口
    class user implements splSubject
    {
        public $lognum;
        public $hobby;
    
        protected $observers = null;
    
        public function __construct($hobby){
    
            $this->lognum = rand(1,10);
            $this->hobby = $hobby;
            $this->observers = new SplObjectStorage();
        }
    
        public function attach(SPLObserver $observer){
            $this -> observers -> attach($observer);
        }
    
        public function detach(SPLObserver $observer){
            $this -> observers -> detach($observer);
    
        }
    
        public function login(){
            $this->notify();
        }
    
        public function notify(){
            $this->observers->rewind();
            while($this->observers->valid()){
                $observer = $this->observers->current();
                $observer->update($this);
                $this->observers->next();
            }
        }
    
    }
    
    
    class secrity implements SPLObserver{
        public function update(SplSubject $subject){
            if($subject->lognum <3){
                echo '安全登录'. $subject->lognum ;
            }else{
                echo '不安全登录'. $subject->lognum ;
            }
        }
    }
    
    
    class ad implements SPLObserver{
        public function update(SplSubject $subject){
                echo $subject->hobby;
        }
    }
    
    
    $user = new user('taiqiu ');
    $user->attach(new secrity());
    $user->attach(new ad());
    $user->login();

    自动调用了安全模块的登录次数 和 广告模块推荐广告

  • 相关阅读:
    开启mysql远程登录
    InfluxDB安装及配置
    基于ssh反向代理实现的远程协助
    小工具之进程守护器
    生成freeswitch事件的几种方式
    freeswitch模块之event_socket
    freeswitch对接其它SIP设备
    freeswitch注册过程分析
    redis参考文档
    创建型模式之Builder模式及实现
  • 原文地址:https://www.cnblogs.com/long613/p/7682458.html
Copyright © 2011-2022 走看看