The Observer pattern (Observer pattern) of the design pattern (behavioral type)

Source: Internet
Author: User

PS One sentence: Eventually choose Csdn to organize the publication of the knowledge points of these years, the article parallel migration to CSDN. Because CSDN also support markdown grammar, Ah!

"Craftsman Joshui Http://blog.csdn.net/yanbober" read the previous article "design mode (structure) of the proxy pattern" http://blog.csdn.net/yanbober/article/ details/45480965

Overview

The observer pattern is used to establish a dependency between objects and objects, and other objects are automatically notified when one object changes, and other objects respond accordingly. In the Observer pattern, the object of the change is called the observation target, and the object being notified is called the Observer, and an observation target can correspond to multiple observers, and there can be no interaction between the observers, and the observer can be added and removed as needed, making the system easier to expand. A software system often requires that some other object make corresponding changes when the state of an object changes. There are many design options to do this, but in order to make the system easy to reuse, a low-coupling design should be chosen. Reducing the coupling between objects facilitates the reuse of the system, but designers need to enable these low-coupling objects to maintain coordination of actions and ensure a high degree of collaboration. The Observer pattern is the most important of the various design scenarios that satisfy this requirement.

Core

Concept: defines a one-to-many dependency between objects, so that whenever an object state changes, its dependent objects are notified and automatically updated. The alias of the Observer pattern includes the publish-subscribe (publish/subscribe) mode, the Model-view (Model/view) mode, the source-listener (Source/listener) mode, or the slave (dependents) mode. The Observer pattern is an object-behavioral pattern.

Observer pattern structure important core modules:

Abstract Theme (Subject)

Abstract theme Roles keep all references to observer objects in a single aggregation (such as a ArrayList object), and each subject can have any number of observers. Abstract topics provide an interface that can add and remove observer objects, and abstract subject roles are also known as abstract Observer (Observable) roles.

Specific topics (ConcreteSubject)

The status is deposited into the specific observer object, and all registered observers are notified when the internal state of the specific subject changes. The specific subject role is also called the specific Observer (concrete Observable) role.

Abstract Observer (Observer)

Define an interface for all specific observers and update yourself when you get notifications of the topic, which is called the update interface.

Specific Observer (Concreteobserver)

Stores the state of the theme from its own state. The specific observer role implements the update interface required by the abstract observer role in order to reconcile the state of itself with the state of the subject. If desired, the specific observer role can maintain a reference to a specific subject object.

Usage Scenarios

An abstract model has two facets, one of which relies on another, encapsulating the two aspects in separate objects so that they can be individually changed and reused.

The change of one object causes one or more other objects to change, without knowing exactly how many objects will change or who they are.

A trigger chain needs to be created in the system, the behavior of the A object will affect the B object, and the behavior of the B object will affect the C object ..., you can use the observer pattern to create a chain-triggered mechanism.

Program Ape Instance

A simple example:

The following is a simple observer pattern. No longer explain too much:

 PackageYanbober.github.io;ImportJava.util.ArrayList;ImportJava.util.List;//Abstract Observer role classInterface Observer {voidUpdate (String state);}//Specific observer role classesClass Programmonkeyobserver implements Observer {@Override     Public void Update(String State) {System.out.println ("Programer look the SDK download process is:"+state); }}//Abstract Theme role ClassAbstractClass Subject {Privatelist<observer> list =NewArraylist<> (); Public void Attach(Observer Observer)    {LIST.ADD (Observer); } Public void Detach(Observer Observer)    {LIST.REMOVE (Observer); } Public void motifyobservers(String newstate) { for(Observer observer:list)        {observer.update (newstate); }    }}//Specific theme role ClassesClass Sdkdownloadsubject extends Subject { Public void Netprocesschange(String data) { This. motifyobservers (data); }}//Client Public  class Main {     Public Static void Main(string[] args) {Sdkdownloadsubject Sdkdownloadsubject =NewSdkdownloadsubject (); Observer Observer =NewProgrammonkeyobserver ();        Sdkdownloadsubject.attach (Observer); Sdkdownloadsubject.netprocesschange ("1%"); Sdkdownloadsubject.netprocesschange ("51%"); Sdkdownloadsubject.netprocesschange ("100%"); }}

Upgrade Gear: the viewer mode of the push-pull method.

Example of the observer pattern of the push mode:

The subject object pushes the details of the topic to the observer, and the information that is pushed is usually all or part of the data of the subject object, regardless of whether or not the observer needs them.

The simple example above is actually an example of how an observer pattern is pushed, and not much is explained here.

Example of the observer pattern of the Pull mode:

The Subject object transmits only a small amount of information when it notifies the observer. If the observer needs more specific information, the Observer takes the initiative to get to the subject object, which is equivalent to the observer pulling data from the subject object. In the general implementation of this model, the subject object itself is passed to the observer through the update () method, which can be obtained by this reference when the observer needs to obtain the data.

The following code is an example of a push mode (simple example) modification to the pull mode, which does not explain too much here:

 PackageYanbober.github.io;ImportJava.util.ArrayList;ImportJava.util.List;//Abstract Observer role classInterface Observer {voidUpdate (Subject Subject);}//Specific observer role classesClass Programmonkeyobserver implements Observer {@Override     Public void Update(Subject Subject)        {String state = ((sdkdownloadsubject) subject). GetState (); System.out.println ("Programer look the SDK download process is:"+state); }}//Abstract Theme role ClassAbstractClass Subject {Privatelist<observer> list =NewArraylist<> (); Public void Attach(Observer Observer)    {LIST.ADD (Observer); } Public void Detach(Observer Observer)    {LIST.REMOVE (Observer); } Public void motifyobservers() { for(Observer obs:list) {Obs.update ( This); }    }}//Specific theme role ClassesClass Sdkdownloadsubject extends Subject {PrivateString mstate; PublicStringgetState() {returnMstate; } Public void Netprocesschange(String data) {mstate = data; This. Motifyobservers (); }}//Client Public  class Main {     Public Static void Main(string[] args) {Sdkdownloadsubject Sdkdownloadsubject =NewSdkdownloadsubject (); Observer Observer =NewProgrammonkeyobserver ();        Sdkdownloadsubject.attach (Observer); Sdkdownloadsubject.netprocesschange ("1%"); Sdkdownloadsubject.netprocesschange ("51%"); Sdkdownloadsubject.netprocesschange ("100%"); }}

Continue to upgrade the awesome Java standard supported Watcher mode:

In the Java language Java.util Library, a observable class and a observer interface are provided, which form the Java language support for the Observer pattern.

The Observer interface only defines an update () method, which is called by the Notifyobservers () method of the Observer object when the state of the object being observed changes.

The observable class is the base class for the Observer class. Java.util.Observable provides a public way to support the Observer object, where two of these methods are important for observable subclasses: one is setchanged () and the other is Notifyobservers (). The first method setchanged () is called and an internal tag variable is set, representing the state of the object being observed to change. The second is notifyobservers (), which, when called, invokes the update () method of all registered observer objects so that the observer objects can update themselves.

The following example is the use of the observer pattern supported by the Java library, and the specifics are not explained:

 PackageYanbober.github.io;Importjava.util.Observable;ImportJava.util.Observer;//ObserverClass Programmonkeyobserver implements Observer { Public Programmonkeyobserver(Observable Obs) {Obs.addobserver ( This); }@Override     Public void Update(Observable o, Object Arg) {System.out.println ("Programer look the SDK download process is:"+ ((sdkdownloadobservable) O). GetState ()); }}//The person being observedClass Sdkdownloadobservable extends Observable {PrivateString mstate; PublicStringgetState() {returnMstate; } Public void Netprocesschange(String data) {mstate = data; This. setchanged (); This. Notifyobservers (); }}//Client Public  class Main {     Public Static void Main(string[] args) {Sdkdownloadobservable sdkdownloadobservable =NewSdkdownloadobservable ();NewProgrammonkeyobserver (sdkdownloadobservable); Sdkdownloadobservable.netprocesschange ("1%"); Sdkdownloadobservable.netprocesschange ("51%"); Sdkdownloadobservable.netprocesschange ("100%"); }}

Continue upgrade – Interaction between objects (event handling):

With the three progressive observer pattern examples above, you'll need to continue with the awesome quest upgrade ... Go,go,go ...

Back to whether God still remembers the basic example of the front, there is wood found in fact, Android development similar to fragment and activity and fragment and fragment interaction and other operations to use the interface mode is the Observer mode, but there is a little different from the writing here. Haha, that's what's next.

In a DEM model, a target role (such as an interface component) is responsible for publishing an event, and the Observer role (the event handler) can subscribe to the event that it is interested in to the target. When a specific target produces an event, it notifies all subscribers. The publisher of the event is called the event source, and the Subscriber is called the event Listener, which in the process can also pass event-related information through the event object. Event handlers can be implemented in the implementation class of an event listener, so an event listener can also be called an event-handling object. The event source object, the event listener object (the event handler object), and the event object form the three elements of the Java event Processing model.

I take a go, powerful Google Android source control Xxxlistener is not all similar mode it!!! Haha, that's so duang!!!. This is not to say that in event handling, it is common to use a one-to-two observer pattern, rather than the difference between a pair of observer patterns!

The instance program is omitted, and Android has an event model everywhere, regardless of the source code or itself.

The revolution is not yet successful, comrades still need to work hard. Continue to blame the Upgrade Observer mode (MVC Software framework model):

The observer pattern is also applied in the MVC (Model-view-controller) architecture of the software World, MVC is an architectural pattern that contains three roles: model, view, and controller. Where the model corresponds to the observed target in the observer pattern, and the view corresponds to the Observer, the Controller can act as a mediator between the two. When the data in the model layer changes, the view layer automatically changes its display content.

sum up a

Observer Pattern Advantages:

    • The Observer pattern creates an abstract coupling between the observer and the Observer. What the observer role knows is a list of specific observers, each of which conforms to an abstract observer's interface. The observer does not know any specific observer, it only knows that they all have a common interface. Because the observer and the observer are not tightly coupled, they can belong to different levels of abstraction. If both the observer and the observer are thrown together, the object inevitably crosses the abstraction and materialization levels.

Observer pattern Disadvantage:

    • If an observer object has many direct and indirect observers, all observers are informed that it will take a lot of time.
    • If there is a cyclic dependency between the observers, the observed will trigger a cyclic call between them, causing the system to crash. It is important to pay special attention to this when using the Observer pattern.
    • If the notice to the Observer is asynchronous delivery via another thread, the system must ensure that the delivery is carried out in a self-consistent manner.
    • Although the observer pattern allows the observer to know that the object being observed has changed, the Observer pattern does not have a mechanism for the observer to know how the observed object has changed.

"Craftsman Joshui Http://blog.csdn.net/yanbober" Continue reading "to be continued ... 》

The Observer pattern (Observer pattern) of the design pattern (behavioral type)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.