Defined
Defines a one-to-many dependency between objects so that when each object changes state, all objects that depend on it are notified and updated automatically.
Uml
Advantages
- It is loosely coupled between the observer and the observed, and can be individually changed independently of each other.
- Subject when sending a broadcast notification, you do not need to specify a specific observer,observer to decide whether to subscribe to subject notifications.
- Comply with most grasp principles and common design principles, high cohesion and low coupling.
Disadvantages
- Loose coupling can cause code relationships to be less obvious and sometimes difficult to understand.
- If an object is subscribed by a large number of observers, there may be an efficiency issue when broadcasting notifications. (After all, just a simple traversal)
Application Scenarios
- Updates to an object's state require other objects to be updated synchronously, and the number of other objects is dynamically variable.
- Objects only need to notify their own updates to other objects without needing to know the details of other objects.
Example
Implement an example of a simple observer and a observed person.
Java
1 Importjava.util.ArrayList;2 Importjava.util.List;3 4 Public classMain5 {6 Public Static voidMain (string[] args)7 {8Subject Sub =NewConcreteSubject ();9Sub.addobserver (NewConcreteObserver1 ());//Add Observer 1TenSub.addobserver (NewConcreteObserver2 ());//Add Observer 2 One sub.dosomething (); A } - - /** the * Observe the interface - */ - Public InterfaceObserver - { + voidupdate (); - } + A /** at * The Observer base class - */ - Public Static Abstract classSubject - { - PrivateList<observer> Obs =NewArraylist<>(); - in Public voidaddobserver (Observer obs) - { to This. Obs.add (OBS); + } - the Public voiddelobserver (Observer obs) * { $ This. Obs.remove (OBS);Panax Notoginseng } - the protected voidNotifyobserver () + { A for(Observer o:obs) the { + o.update (); - } $ } $ - Public Abstract voiddosomething (); - } the - /**Wuyi * Viewer Object 1 the */ - Public Static classConcreteObserver1ImplementsObserver Wu { - Public voidUpdate () About { $SYSTEM.OUT.PRINTLN ("Observer 1 receives the message and processes it. "); - } - } - A /** + * Viewer Object 2 the */ - Public Static classConcreteObserver2ImplementsObserver $ { the Public voidUpdate () the { theSYSTEM.OUT.PRINTLN ("Observer 2 receives the message and processes it. "); the } - } in the /** the * The specific person being observed About */ the Public Static classConcreteSubjectextendsSubject the { the Public voiddosomething () + { -System.out.println ("The observed event is reversed"); the This. Notifyobserver ();Bayi } the } the}
View Code
Behavior class pattern (VII): Observer (Observer)