>php教程 >php手册 >观察者模式,观察者模式类图

观察者模式,观察者模式类图

WBOY
WBOY원래의
2016-06-13 09:07:131618검색

观察者模式,观察者模式类图

观察者模式

<?<span>php
    </span><span>//</span><span>定义观察者调用接口</span>
    <span>class</span><span> transfer{
        </span><span>protected</span> <span>$_observers</span> = <span>array</span><span>();
        
        </span><span>//</span><span>注册对象</span>
        <span>public</span> <span>function</span> register(<span>$sub</span><span>){
            </span><span>$this</span>->_observers[] = <span>$sub</span><span>;    
        }
        
        </span><span>//</span><span>外部统一调用</span>
        <span>public</span> <span>function</span><span> trigger(){
            </span><span>if</span>(!<span>empty</span>(<span>$this</span>-><span>_observers)){
                </span><span>foreach</span>(<span>$this</span>->_observers <span>as</span> <span>$observer</span><span>){
                    </span><span>$observer</span>-><span>update();
                }    
            }
        }
    }
    
    </span><span>//</span><span>观察者接口</span>
    <span>interface</span><span> obserable{
        </span><span>public</span> <span>function</span><span> update();
    }
    
    </span><span>//</span><span>实现观察者</span>
    <span>class</span> listen <span>implements</span><span> obserable{
        </span><span>public</span> <span>function</span><span> update(){
            </span><span>echo</span> 'now first time you need to do listen<br/>'<span>;
        }
    }
    
    </span><span>class</span> read <span>implements</span><span> obserable{
        </span><span>public</span> <span>function</span><span> update(){
            </span><span>echo</span> 'now first time you need to read<br/>'<span>;
        }
    }
    
    </span><span>class</span> speak <span>implements</span><span> obserable{
        </span><span>public</span> <span>function</span><span> update(){
            </span><span>echo</span> 'now first time you need to speak<br/>'<span>;
        }
    }
    
    </span><span>class</span> write <span>implements</span><span> obserable{
        </span><span>public</span> <span>function</span><span> update(){
            </span><span>echo</span> 'now first time you need to write<br/>'<span>;
        }
    }
    
    </span><span>$transfer</span> = <span>new</span><span> transfer();
    </span><span>$transfer</span>->register(<span>new</span><span> listen());
    </span><span>$transfer</span>->register(<span>new</span><span> read());
    </span><span>$transfer</span>->register(<span>new</span><span> speak());
    </span><span>$transfer</span>->register(<span>new</span><span> write());
    </span><span>$transfer</span>-><span>trigger();
    
    
    
    
    
    
    
    
    
    
    
    
    </span>

 

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.