I. Introduction to the Observer pattern
When an object changes, other objects that depend on the object are notified and will change! Objects are a one-to-many relationship.
Two. Practical application
Chat room, message subscription
In these scenarios, subscribers and chat clients are called observers, and data that needs to be synchronized to multiple subscribers is encapsulated into objects.
Called a target.
Three. Mode core
The Observer pattern is a one-to-many notification, and when an object changes, he needs to tell each object.
How to notify the Observer:
1) Push: The Observer can only passively accept the message
2) Pull: The Observer can decide whether to receive the message at its own discretion.
The message object holds all observers through the container, and when the message is updated, each observer is notified of the update message by traversing the container.
Four. Simple code implementation
Package Com.lz.observer; /* */Publicinterface iobserver {void Update ( Subject sub);}
PackageCom.lz.observer; Public classObserverImplementsiobserver{Private intThisvalue; Public intGetthisvalue () {returnThisvalue; } Public voidSetthisvalue (intthisvalue) { This. Thisvalue =Thisvalue; } @Override Public voidUpdate (Subject sub) {Thisvalue=( (ConcreteSubject) sub). GetValue (); }}
PackageCom.lz.observer;Importjava.util.ArrayList;Importjava.util.List; Public classSubject {/** Storage of the viewer's container*/ protectedlist<iobserver> list =NewArraylist<iobserver>(); Public voidaddiobserver (IObserver iobs) {list.add (iobs); } Public voidRemove (IObserver iobs) {list.remove (iobs); } /** All observers will be notified when the status is changed*/ protected voidNotifyallobserver () { for(IObserver iobserver:list) {iobserver.update ( This); } }}
package Com.lz.observer; public class ConcreteSubject extends subject{ private int value; public int GetValue () { value; public void SetValue (int this . Value = value; Notifyallobserver (); }}
PackageCom.lz.observer; Public classClient { Public Static voidMain (string[] args) {ConcreteSubject sub=NewConcreteSubject (); /** Viewer*/Observer OBS1=NewObserver (); Observer OBS2=NewObserver (); Observer OBS3=NewObserver (); Sub.addiobserver (OBS1); Sub.addiobserver (OBS2); Sub.addiobserver (OBS3); Sub.setvalue (100); System.out.println (Obs1.getthisvalue ()); System.out.println (Obs2.getthisvalue ()); System.out.println (Obs3.getthisvalue ()); Sub.setvalue (200); System.out.println (Obs1.getthisvalue ()); System.out.println (Obs2.getthisvalue ()); System.out.println (Obs3.getthisvalue ()); }}
Java design Pattern GOF23 12 Watcher pattern