Home >Backend Development >PHP Tutorial >Detailed explanation of the observer pattern of PHP design patterns
Define a one-to-many dependency relationship between objects, so that whenever the state of an object changes, its related dependent objects are notified and automatically updated. The aliases of the observer pattern include Publish/Subscribe mode, Model/View mode, Source/Listener mode or Dependents mode. Observer pattern is an object behavior pattern. Observer PatternDefine one-to-many dependencies of objects, so that when an object changes state, all its dependencies will be notified and automatically updated!
<?php /** * 观察者模式 * @author: Mac * @date: 2012/02/22 */ abstract class Pa { private $_observers = array(); public function register($sub) { } public function trigger() { } } class Paper extends Pa { /* 主题 */ private $_observers = array(); // 存放new的对象 public function register($sub) { /* 注册观察者 */ $this->_observers[] = $sub; } public function trigger() { /* 外部统一访问 */ if (!empty($this->_observers)) { foreach ($this->_observers as $observer) { $observer->update(); } } } } /** * 观察者要实现的接口 */ interface Observerable { public function update(); } class Subscriber1 implements Observerable //观察者 { public function update() { echo "观察者1收到执行通知 执行完毕\n"; } } class Subscriber2 implements Observerable //观察者2 { public function update() { echo "观察者2收到执行通知 执行完毕\n"; } } /* 测试 */ $paper = new Paper(); $paper->register(new Subscriber1()); $paper->trigger();
The observer pattern is a very frequently used design pattern. Whether it is a mobile application, a web application or a desktop application, the observer pattern is almost everywhere. It provides a way to achieve linkage between objects. A complete solution, the observer pattern can be used in any scenario involving one-to-one or one-to-many object interaction.
Related recommendations:
What you don’t understand about the PHP observer pattern
Code examples of PHP observer pattern
The above is the detailed content of Detailed explanation of the observer pattern of PHP design patterns. For more information, please follow other related articles on the PHP Chinese website!