observer pattern

Observer pattern: defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

oo principles: strive for loosely coupled designs between objects that interact.

How observer pattern works

let's look at how newspaper or magazine subscriptions work:
1. A newspaper publisher goes into business and begins publishing newspapers.
2. You subscribe to a particular publisher, and every time there's a new edition it gets delivered to you. As long as you remain a subscriber, you get new newspapers
3. You unsubscribe when you don't want papers anymore, and they stop being delivered
4. While the publisher remains in business, people, hotels, airlines and other businesses constantly subscribe and unsubscribe to the newspaper.

Publishers+subscribers = observer pattern

if you understand newspaper subscriptions, you pretty much understand the Observer Pattern, only we call the publisher the [b]SUBJECT [/b] and the subscribers the [b]OBSERVERS[/b]

Illustration
[IMG]http://i45.tinypic.com/2jes50k.jpg[/IMG]

the duck object isn't an observer, it wont get notified when the subject's data changes.

How does the duck object become an observer
1. register/subscribe
[IMG]http://i47.tinypic.com/2whkpyp.jpg[/IMG]

2.The duck object is now an official observer
duck is psyched. he's on the list and is waiting with great anticipation for the next notification.
[IMG]http://i45.tinypic.com/fjm9no.jpg[/IMG]

3. the subject gets a new data value
Now duck and all the rest of observers get a notification that the subject has changed
[IMG]http://i48.tinypic.com/309lamc.jpg[/IMG]


java built-in support of observer pattern
[IMG]http://i50.tinypic.com/9is6rp.jpg[/IMG]


bullet point
* The observer pattern defines a one-to-many relationship between objects
* Subjects, or as we also know them, Observables, update Observers using a common interface
* Observers are loosely coupled in that the Observable knows nothing about them, other than that they implement the Observer interface
* You can push or pull data from Observable when using the pattern(pull is considered more "correct")
* Don't depend on a specific order of notification for your Observers.
* Java has several implementations of the Observer Pattern, including the general purpose java.util.Observable.
* Watch out for issues with the java.util.Observable implementation.
* Don't be afraid to create your own Observable implementation if needed
* Swing makes heavy use of the Observer Pattern. as do many GUI frameworks.
* You'll also find the pattern in many other places, including JavaBeans and RMI
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值