美文网首页PHP笔记
PHP 利用SPL实现观察者模式

PHP 利用SPL实现观察者模式

作者: 零一间 | 来源:发表于2018-02-08 16:51 被阅读21次
    <?php
    
    //-----------------------------------------------
    // 利用SPL实现观察者模式
    //-----------------------------------------------
    
    
    /**
     * 订单管理系统
     * Class OmsObserver
     */
    class  OmsObserver implements SplObserver
    {
    
        public function update(SplSubject $subject) {
            echo ' module-name: oms  order-no: ' . $subject->getOrderNumber();
            // todo
            echo ' result: send success' . PHP_EOL;
        }
    }
    
    /**
     * 仓库管理系统
     * Class WmsObserver
     */
    class  WmsObserver implements SplObserver
    {
    
        public function update(SplSubject $subject) {
            echo ' module-name: wms  order-no: ' . $subject->getOrderNumber();
            // todo
            echo ' result: send success' . PHP_EOL;
        }
    }
    
    /**
     * 运输管理系统
     * Class TmsObserver
     */
    class  TmsObserver implements SplObserver
    {
    
        public function update(SplSubject $subject) {
            echo ' module-name: tms  order-no: ' . $subject->getOrderNumber();
            // todo
            echo ' result: send success' . PHP_EOL;
        }
    }
    
    class OrderCenterSubject implements SplSubject
    {
    
        private $_observers;
        private $_orderNumber;
    
        public function __construct($orderNumber) {
            $this->_observers = new SplObjectStorage();
            $this->_orderNumber = $orderNumber;
        }
    
        public function attach(SplObserver $observer) {
            $this->_observers->attach($observer);
        }
    
        public function detach(SplObserver $observer) {
            $this->_observers->detach($observer);
        }
    
        public function notify() {
            foreach ($this->_observers as $observer) {
                $observer->update($this);
            }
        }
    
        public function getOrderNumber() {
            return $this->_orderNumber;
        }
    
    }
    
    //测试
    $omsObserver = new OmsObserver();
    $wmsObserver = new WmsObserver();
    $tmsObserver = new TmsObserver();
    $orderCenterSubject = new OrderCenterSubject("10030522161715");
    $orderCenterSubject->attach($omsObserver);
    $orderCenterSubject->attach($wmsObserver);
    $orderCenterSubject->attach($tmsObserver);
    $orderCenterSubject->notify();
    
    

    相关文章

      网友评论

        本文标题:PHP 利用SPL实现观察者模式

        本文链接:https://www.haomeiwen.com/subject/vvittftx.html