Home > Backend Development > PHP Tutorial > PHP 观察者设计模式测试代码笔记

PHP 观察者设计模式测试代码笔记

WBOY
Release: 2016-06-20 12:34:21
Original
1015 people have browsed it

<?php/** * 所有观察者必须实现的接口 * Interface Observer */interface Observer {    public function update();}/** * 观察者1 * Class sendEmail */class SendEmail implements Observer {    public function update()    {        echo 'the email has been send <br>';    }}/** * 观察者2 * Class SaveName */class SaveName implements Observer {    public function update()    {        echo 'the name has been save <br>';    }}/** * 被观察者接口 * Interface Observered */interface  Observered {    public function attach($object);    public function delete($object);    public function notify();}/** * 被观察者 * Class User */class User implements Observered {    public $observers = array();    /**     * 注册观察者     * @param $object     */    public function attach($object)    {        if (!is_object($object)) {            exit('it is not an object');        }        if ($object instanceof Observer) {            if (!in_array($object,$this->observers)) {                $this->observers[] = $object;            }        } else {            echo get_class($object) . ' is disable <br>';        }    }    /**     * 删除观察者     * @param $object     */    public function delete($object)    {        if (in_array($object,$this->observers)) {            $index = array_search($object,$this->observers);            unset($this->observers[$index]);        }    }    /**     * 通知所有观察者     */    public function notify()    {        foreach ($this->observers as $val) {            $val->update();        }    }    /**     * 被观察者自己的业务     */    public function printName()    {        echo 'I have been observing <br>';    }}    $object = new User();    $object->attach(new SendEmail()); //注册观察者1    $object->attach(new SaveName());  //注册观察者2    $object->printName();             //被观察者自己的业务    $object->notify();                //通知所有的观察者
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template