Observer Pattern
Observer pattern (Observer), when the state of an object changes, all objects that rely on it will receive notifications and automatically update.
The role in the pattern
phpDemo
<code><span><?php</span><span>abstract</span><span><span>class</span><span>EventGenerator</span>{</span><span>private</span><span>$observer_arr</span> = <span>array</span>(); <span>/* 添加观察者 */</span><span>public</span><span><span>function</span><span>addObserver</span><span>( Observer <span>$observer</span>)</span> {</span><span>$this</span>->observer_arr[] = <span>$observer</span>; } <span>/* 通知所有观察者 */</span><span>public</span><span><span>function</span><span>notify</span><span>()</span> {</span><span>foreach</span> (<span>$this</span>->observer_arr <span>as</span><span>$observer</span>) { <span>$observer</span>->update(); } } } </span></code>
<code><span><span>class</span><span>Event</span><span>extends</span><span>EventGenerator</span>{</span><span>public</span><span><span>function</span><span>trigger</span><span>()</span> {</span><span>echo</span><span>'event happen!<br/>'</span>; <span>//当事件发生时,通知所有观察者</span><span>$this</span>->notify(); } } </code>
<code><span><?php</span><span><span>interface</span><span>Observer</span>{</span><span>//自动更新</span><span><span>function</span><span>update</span><span>()</span>;</span> } </code>
<code><span><span>class</span><span>Observer1</span><span>implements</span><span>Observer</span>{</span><span>//实现update方法</span><span>public</span><span><span>function</span><span>update</span><span>()</span> {</span><span>echo</span><span>'observer1 update<br/>'</span>; } } <span><span>class</span><span>Observer2</span><span>implements</span><span>Observer</span>{</span><span>//实现update方法</span><span>public</span><span><span>function</span><span>update</span><span>()</span> {</span><span>echo</span><span>'observer2 update<br/>'</span>; } } </code>
<code><span>$obj</span> = <span>new</span> Event(); <span>//添加观察者</span><span>$obj</span>->addObserver(<span>new</span> Observer1()); <span>$obj</span>->addObserver(<span>new</span> Observer2()); <span>$obj</span>->trigger(); </code>
Pattern summary
The above introduces the observer pattern, one of the PHP design patterns, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.