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
observer pattern_第1张图片

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
observer pattern_第2张图片

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.
observer pattern_第3张图片

3. the subject gets a new data value
Now duck and all the rest of observers get a notification that the subject has changed
observer pattern_第4张图片


java built-in support of observer pattern
observer pattern_第5张图片


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

你可能感兴趣的:(swing,REST,OO)