|
| 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 | +class PostOffice |
| 16 | + constructor: () -> |
| 17 | + @subscribers = [] |
| 18 | + sendNewItemReleased: (item) -> |
| 19 | + subscriber.callback(item) for subscriber in @subscribers when subscriber.item is item |
| 20 | + return |
| 21 | + subscribe: (to, onNewItemReleased) -> |
| 22 | + @subscribers.push({'item':to, 'callback':onNewItemReleased}) |
| 23 | +class MagazineSubscriber |
| 24 | + onNewMagazine: (item) -> |
| 25 | + alert "I've got new "+item |
| 26 | +class NewspaperSubscriber |
| 27 | + onNewNewspaper: (item) -> |
| 28 | + alert "I've got new "+item |
| 29 | + |
| 30 | +postOffice = new PostOffice() |
| 31 | +sub1 = new MagazineSubscriber() |
| 32 | +sub2 = new NewspaperSubscriber() |
| 33 | +postOffice.subscribe "Mens Health", sub1.onNewMagazine |
| 34 | +postOffice.subscribe "Times", sub2.onNewNewspaper |
| 35 | +postOffice.sendNewItemReleased "Times" |
| 36 | +postOffice.sendNewItemReleased "Mens Health" |
| 37 | +{% endhighlight %} |
| 38 | + |
| 39 | +## Discussion |
| 40 | + |
| 41 | +Here you have an observer object (PostOffice) and observable objects (MagazineSubscriber, NewspaperSubscriber). |
| 42 | +To be notified about an event of publishing new periodical observable object should make subscribtion on PostOffice. |
| 43 | +Every of subscribed objects is stored internaly in the PostOffice array of subscribers. |
| 44 | +Every subscriber is notified on new concrete periodical is published. |
0 commit comments