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();

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

  • 相关阅读:
    AngularJs $location 和 $window
    AngularJS——自定义服务详解(factory、service、provider)
    angularAMD+requireJs
    angular ui-router时要使用html5Mode=true
    CSS3的calc()使用
    React Ajax this.IsMounted() is not a function
    css有用的代码片段
    8908
    454
    234
  • 原文地址:https://www.cnblogs.com/long613/p/7682458.html
Copyright © 2011-2022 走看看