definition: defines a one-to-many dependency between objects so that when each object changes state, all objects that depend on it are notified and automatically updated.
Type: object behavior pattern
alias : Publish-Subscribe (publish-subscribe)
class Diagram:
In software systems, there is often a need to change the state of an object, and some objects associated with it are changed accordingly. For example, we're going to design a function of a right-click menu, if you click the right mouse button in the effective area of the software, a menu pops up; for example, we want to design an automated deployment function, like eclipse development, as long as you modify the file, eclipse will automatically deploy the modified files to the server. These two functions have a similar place, that is, an object to listen to another object at all times, as long as its state changes, and then to make the corresponding action. In fact, there are many options to achieve this, but it is no doubt that the use of the observer model is a mainstream choice.
The Observer pattern describes how to build this relationship. The key objects in this model are the target (subject) and the Observer (Observer). A goal can have any number of observers who depend on it. Once the status of the target has changed, all observers are notified. As a response to this notification, each observer queries the target to synchronize its state with the target State.
This interaction is also known as Publish-subscribe (publish-subscribe). The target is the publisher of the notification. It does not need to know who is its observer when it gives notice. You can subscribe to any number of observers and receive notifications.
structure of the Observer pattern
In the most basic observer model, the following four roles are included: The observed: from the class diagram, you can see that there is a vector container in the class to hold the Observer object (the reason that vector is used instead of list is because the vector is safe when multithreaded operations, And the list is unsafe), the vector container is the core of the observed class, and there are three other methods: The Attach method is to add the Observer object to the container; The detach method is to remove the observer object from the container; The Notify method is to call the corresponding method of the observer object sequentially. This role can be an interface, an abstract class, or a specific class, because in many cases it will be mixed with other patterns, so there are more instances of using abstract classes. Observer: The Observer role is typically an interface that has only one update method, which is invoked when the observed state changes. specific observers: This role is used to facilitate extension, and specific business logic can be defined in this role. specific Observer: the concrete implementation of the Observer interface, in which the logic to be dealt with when the observed object's state changes is defined.
Observer Pattern Code implementation
Abstract target Abstraction class Subject {private vector<observer> obs = new vector<observer> ();
The Observer list needs to synchronize public synchronized void Registerobserver (Observer obs) {this.obs.add (OBS);
Public synchronized void Unregisterobserver (Observer obs) {this.obs.remove (OBS);
///Send notification message protected void Notifyobserver () {for (Observer o:obs) {o.update ();
} public abstract void dosomething ();
}//Specific target class ConcreteSubject extends Subject {public void dosomething () {System.out.println ("observed event occurrence");
This.notifyobserver ();
}///Observer interface interface Observer {public void Update ();} Specific observer, implementation update operations class ConcreteObserver1 implements Observer {public void update () {SYSTEM.OUT.PRINTLN ("Observer 1 receives information, keep abreast Row processing.
"); The class ConcreteObserver2 implements Observer {public void update () {SYSTEM.OUT.PRINTLN ("Observer 2) received the message and processed it."
"); } public class Observerclient {/** * @param args/public static void main (string[] args) {Subject sub = n EW CONCREtesubject (); Sub.registerobserver (New ConcreteObserver1 ()); Add Observer 1 Sub.registerobserver (New ConcreteObserver2 ());
Add Observer 2 sub.dosomething (); }
}
Run results
The observed event occurs
The Observer 1 receives the information and processes it.
The Observer 2 receives the information and processes it.
By running the results, we can see that we have only called the subject method, but at the same time the relevant methods of the two observers are called simultaneously. A careful look at the code, in fact, is very simple, it is in the subject class to associate the Observer class, and in the DoSomething method to traverse the Observer Update method on the line.
the pros and cons of the Observer model
The abstract coupling between the target and the observer is only known by a target that has a series of observers, each conforming to the simple interface of the abstract observer class. The target does not know which specific class any observer belongs to. The coupling between the target and the observer is abstract and minimal. Because the target and the observer are not tightly coupled, they can belong to different levels of abstraction in a system. A target object at a lower level can communicate with a higher-level observer and notify it, thus maintaining the integrity of the system hierarchy. Support for broadcast traffic is not like a regular request, the target sends a notification that does not need to specify its recipient. The notification is automatically broadcast to all relevant objects that have been registered with the target object. The target does not care about how many objects are interested in them, and its only responsibility is to inform its observers. This gives you the freedom to add and remove observers at any time. Processing or ignoring a notification depends on the observer. Unexpected updates because an observer does not know the existence of other observers, it may be ignorant of the ultimate cost of changing the target. A seemingly harmless operation on the target may cause a series of updates to the observer and those objects that depend on the observer. In addition, if the dependency criteria are defined or maintained improperly, they often cause incorrect updates, which are often difficult to capture.
Applicability
You can use the observer pattern in any of the following situations:
When an abstract model has two aspects, one aspect is dependent on another. Encapsulate the two in separate objects so that they can be changed and reused independently of each other. When a change in an object needs to change other objects at the same time, it is not known exactly how many objects are to be changed. When an object must notify other objects, it cannot assume that other objects are. In other words, you don't want these objects to be tightly coupled.
Summary
In the Java language, there is an interface observer and its implementation class observable, which is often implemented for the observer role. We can see how these two classes are used in the JDK API documentation.
Those who have done VC + +, JavaScript dom, or AWT development are amazed by their event handling, understanding the observer pattern, and have a certain understanding of the principle of event handling mechanism. If you want to design an event-triggering mechanism, it is a good choice to use the observer pattern, and the event-handling Dem (Delegate event model delegation) in AWT is implemented using the Observer pattern.