`
frank127
  • 浏览: 10567 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

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 SUBJECT and the subscribers the OBSERVERS

Illustration


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


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.


3. the subject gets a new data value
Now duck and all the rest of observers get a notification that the subject has changed



java built-in support of observer pattern



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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics