オブザーバー パターン
オブザーバー パターン (オブザーバー) では、オブジェクトの状態が変化すると、それに依存するすべてのオブジェクトが通知を受け取り、自動的に更新されます。
パターンの役割
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>
パターンの概要