|
| 1 | +--- |
| 2 | +layout: recipe Observer Pattern |
| 3 | +title: Observer Pattern |
| 4 | +chapter: Design patterns |
| 5 | +--- |
| 6 | +## Problem |
| 7 | + |
| 8 | +You have to notify some objects about an event happen |
| 9 | + |
| 10 | +## Solution |
| 11 | + |
| 12 | +Use an [Observer Pattern](http://en.wikipedia.org/wiki/Observer_pattern) |
| 13 | + |
| 14 | +{% highlight coffeescript %} |
| 15 | + |
| 16 | +class PostOffice |
| 17 | + constructor: () -> |
| 18 | + @subscribers = [] |
| 19 | + notifyNewItemReleased: (item) -> |
| 20 | + subscriber.callback(item) for subscriber in @subscribers when subscriber.item is item |
| 21 | + subscribe: (to, onNewItemReleased) -> |
| 22 | + @subscribers.push {'item':to, 'callback':onNewItemReleased} |
| 23 | + |
| 24 | +class MagazineSubscriber |
| 25 | + onNewMagazine: (item) -> |
| 26 | + alert "I've got new "+item |
| 27 | + |
| 28 | +class NewspaperSubscriber |
| 29 | + onNewNewspaper: (item) -> |
| 30 | + alert "I've got new "+item |
| 31 | + |
| 32 | +postOffice = new PostOffice() |
| 33 | +sub1 = new MagazineSubscriber() |
| 34 | +sub2 = new NewspaperSubscriber() |
| 35 | +postOffice.subscribe "Mens Health", sub1.onNewMagazine |
| 36 | +postOffice.subscribe "Times", sub2.onNewNewspaper |
| 37 | +postOffice.notifyNewItemReleased "Times" |
| 38 | +postOffice.notifyNewItemReleased "Mens Health" |
| 39 | + |
| 40 | +{% endhighlight %} |
| 41 | + |
| 42 | +## Discussion |
| 43 | + |
| 44 | +Here you have an observer object (PostOffice) and observable objects (MagazineSubscriber, NewspaperSubscriber). |
| 45 | +To be notified about an event of publishing new periodical observable object should make subscribtion on PostOffice. |
| 46 | +Every of subscribed objects is stored internaly in the PostOffice array of subscribtions. |
| 47 | +Every subscriber is notified on new concrete periodical is published. |
0 commit comments