define
Defines a one-to-many dependency between objects in which all dependent objects are notified and automatically updated when an object’s state changes.
nature
Trigger linkage
His role
-
Subject (object of observation)
Interface or abstract class of the observed object
-
ConcreteSubject ConcreteSubject
The specific object being observed
-
An Observer
Responsible for receiving notifications of state changes from observed objects
-
ConcreteObserve (Concrete Observer)
A concrete observer that implements the interface defined by the observer role.
The sample code
/** */ public class Coder implements Observer {String name; public Coder(String name) { this.name = name; } @Override public void update(Observable o, Object arg) { System.out.println("Hi, "+ name +" DevTechFrontier updated "+ arg); } @Override public String toString() { return "Coder{" + "name='" + name + '\'' + '}'; }} public class DevTechFronter extends Observable {public void postNewContent(String content){public void postNewContent(String content){ SetChanged (); // notifyObservers(content); }} public class Client {public static void main(String[] args){DevTechFronter DevTechFronter = new DevTechFronter(); // Observer Coder coder1 = new Coder(" coder1 "); Coder coder2 = new Coder("Coder2"); Coder coder3 = new Coder("Coder3"); / / will be registered observer to the list of the observed devTechFronter. AddObserver (coder1); devTechFronter.addObserver(coder2); devTechFronter.addObserver(coder3); / / release devTechFronter. PostNewContent (" this is the new content. "); }}Copy the code
The results
Hi, Coder3 DevTechFrontier updated this is the new content. Hi, Coder2 DevTechFrontier updated this is the new content. Coder1 DevTechFrontier updated this is the New Content.Copy the code
advantages
- Observer pattern to realize the abstraction of the coupling between the observer and target, the original target object changes, need to direct call all the object, but after abstract the observer interface, the target and observer coupling and on an abstract level, that is the target only know observer interface, don’t know specific observer’s class, This enables the previous coupling of the target class and the observer.
- The observer mode implements dynamic linkage. Linkage means that one operation causes other related operations.
disadvantages
- May cause unnecessary operations. Because the observer mode broadcasts communication every time, each observer is called the UPDATE method, regardless of whether the observer needs it or not.
Usage scenarios
- When an abstract model has two aspects, the operation of one aspect depends on the state change of the other aspect, the observer mode can be selected to encapsulate the two aspects into the observer and the target object.
- If you change one object, you need to change other objects.
- When an object must notify other objects, but it is expected to be loosely coupled with other notified objects.