观察者模式

ConcreteObeserver.php

_name = $name;
    }

    public function update(SubjectInterface $subject) {
        echo
        'update oberserver[', $this->_name, '], state: ' . $subject->getState(), PHP_EOL;
    }

}

ObserverInterface.php


Subject.php

_observers[] = $observer;
    }

    public function detach(ObserverInterface $observer) {
        $this->_observers =
        array_filter($this->_observers, function($is_a) use ($observer) {
            return $observer !== $is_a;
        });

        return true;
    }

    public function notify() {
        foreach($this->_observers as $observer) {
            $observer->update($this);
        }
    }

    public function getState() {
        return $this->_state;
    }

    public function setState($state) {
        $this->_state = $state;

        return $this;
    }

}

SubjectInterface.php


main.php

attach($obj_a);
$subject->attach($obj_b);
$subject->setState(1);
$subject->notify();

echo 'drop A', PHP_EOL;

$subject->detach($obj_a);
$subject->setState(2);
$subject->notify();

unset(
    $subject,
    $obj_b,
    $obj_b
);

参考资料:

http://design-patterns.readthedocs.io/zh_CN/latest/behavioral_patterns/observer.html#id15

此条目发表在 DesignPattern 分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*


*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>