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

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

  • 相关阅读:
    Win10 UWP Tile Generator
    Win10 BackgroundTask
    UWP Tiles
    UWP Ad
    Win10 build package error collections
    Win10 八步打通 Nuget 发布打包
    Win10 UI入门 pivot multiable DataTemplate
    Win10 UI入门 导航滑动条 求UWP工作
    UWP Control Toolkit Collections 求UWP工作
    Win10 UI入门 SliderRectangle
  • 原文地址:https://www.cnblogs.com/long613/p/7682458.html
Copyright © 2011-2022 走看看