Observer pattern
Observer mode (Observer), when an object state changes, all objects that depend on it are notified and updated automatically.
Roles in the pattern
- Abstract The Observer (abstract class, convenient extension) stores the Observer object in a container, which provides interfaces such as increasing the observer, revoking the Observer, notifying the Observer (notify)
- A specific observer (concrete class, inherited by the Observer abstract Class) is deposited into the observer that needs to be notified, and when the observer needs to update, the Notify method is called
- An abstract observer (interface or abstract class) provides an updated interface for a specific observer, and updates when notified by the Observer
- Specific observer (concrete class, inheriting or implementing abstract observer) implements the interface of the abstract observer, automatic Update
Phpdemo
Abstract by Observer
abstractclassEventGenerator{private$observer_arr = array(); /* 添加观察者 */publicfunctionaddObserver( Observer $observer) {$this->observer_arr[] = $observer; } /* 通知所有观察者 */publicfunctionnotify() {foreach ($this->observer_arr as$observer) { $observer->update(); } }}
The specific observed person
classEventextendsEventGenerator{publicfunctiontrigger() {echo'event happen!
'; //当事件发生时,通知所有观察者$this->notify(); }}
Abstract Viewer
interfaceObserver{//自动更新functionupdate();}
Specific observers
classObserver1implementsObserver{//实现update方法publicfunctionupdate() {echo'observer1 update
'; }}classObserver2implementsObserver{//实现update方法publicfunctionupdate() {echo'observer2 update
'; }}
Test code
$objnew Event();//添加观察者$obj->addObserver(new Observer1());$obj->addObserver(new Observer2());$obj->trigger();
Pattern Summary
- Pros: The Observer pattern enables low-coupling, non-intrusive notification and automatic update mechanisms
- Cons: Dependencies are not completely lifted, abstract notifier still relies on abstract observers
- Trial scenario: 1. When the change of an object needs to be changed to another object, and it does not know how many objects are to be changed; 2. An abstract type has two aspects, when one aspect depends on the other, then the observer pattern can be encapsulated in separate objects so that they are independently changed and reused
The above describes the PHP design pattern ——— Observer pattern, including the content, I hope to be interested in the PHP tutorial friends helpful.