관찰자 패턴
관찰자 패턴(Observer)은 객체의 상태가 변경되면 이를 의존하는 모든 객체에 통보되고 자동으로 업데이트됩니다.
패턴 내 역할
<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>
위 내용은 PHP 디자인 패턴 중 하나인 옵저버 패턴(Observer Pattern)을 그 내용과 함께 소개한 내용으로, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.