An example of the observer pattern in Java explains _java

Source: Internet
Author: User
Tags mutex

The observer pattern is a behavioral design pattern. The purpose of the observer pattern is that when you are interested in the state of an object, you want to be notified each time it changes. In observer mode, an object that observes the state of another object is called a observer observer, and the object being observed is called the subject observer. According to the GOF rule, the Observer pattern is intended to:

Copy Code code as follows:

Defines a one-to-many dependency between objects, one object state changes, and other associated objects are notified and automatically updated.

Subject (the observed) contains observers who need to be notified when their state changes. Therefore, he should be provided to the observer to register (register) himself and unregister (unregister) his own method. When subject (the observed) changes, it is also necessary to include a method to notify all observers. When notifying the observer, it is possible to push updates, or provide another way to get the updated content.

The observer should have a way to set the Observer object and be able to use it to notify the update.

Java provides a built-in way to implement the observer pattern, java.util.Observable and Java.util.Observer interfaces. However, they are not widely used. Because this implementation is too simple, most of the time we do not want the last extended class to simply implement the observer pattern, because Java classes cannot inherit more.

The Java Messages Services (JMS) messaging Service uses the Observer and command modes to implement the publication and subscription of data between different programs.

The MVC model-view-control framework also uses the observer pattern, which treats the model as the observer, and the view as the Observer. The view can register itself to the model to get the change of the model.

Observer Pattern Example

In this example, we will complete a simple discussion of the topic, which the observer will be able to register. Any changes that are caused by content submissions on this topic will notify all registered observers.

Based on the needs of the subject observer, this is the implementation of a basic subject interface, which sets a specific set of methods that need to be implemented in the concrete classes that subsequently implement the interface.

Copy Code code as follows:

Package com.journaldev.design.observer;

Public interface Subject {

Methods to register and unregister observers
public void register (Observer obj);
public void unregister (Observer obj);

method to notify observers of change
public void notifyobservers ();

Updates from subject
Public Object getUpdate (Observer obj);

}

Now create an associated observer. It requires a way to make subject subordinate to an observer. Another method can accept the subject change notice.

Copy Code code as follows:

Package com.journaldev.design.observer;

Public interface Observer {

method to update the observer, used by subject
public void update ();

Attach with subject to observe
public void Setsubject (Subject sub);
}

This association has been established. Now realize the specific topic.

Copy Code code as follows:

Package com.journaldev.design.observer;

Import java.util.ArrayList;
Import java.util.List;

public class Mytopic implements Subject {

Private list<observer> observers;
Private String message;
private Boolean changed;
Private final Object mutex= new object ();

Public Mytopic () {
This.observers=new arraylist<> ();
}
@Override
public void register (Observer obj) {
if (obj = = null) throw new NullPointerException ("null Observer");
if (!observers.contains (obj)) observers.add (obj);
}

@Override
public void unregister (Observer obj) {
Observers.remove (obj);
}

@Override
public void Notifyobservers () {
List<observer> observerslocal = null;
Synchronization is used to make sure no observer registered after the message is received isn't not notified
Synchronized (MUTEX) {
if (!changed)
Return
observerslocal = new arraylist<> (this.observers);
This.changed=false;
}
for (Observer obj:observerslocal) {
Obj.update ();
}

}

@Override
Public Object getUpdate (Observer obj) {
return this.message;
}

method to post topic
public void PostMessage (String msg) {
SYSTEM.OUT.PRINTLN ("Message Posted to Topic:" +msg);
this.message=msg;
This.changed=true;
Notifyobservers ();
}

}

The implementation of the registration and logoff observer method is very simple, and the additional method PostMessage () will be applied by the client to submit a string message to this topic. Note that Boolean variables are used to track changes in the state of the topic and to inform the observer of such changes. This variable is necessary because if there is no update, but someone calls the Notifyobservers () method, he cannot send the wrong notification information to the observer.

Also note that notifyobservers () uses synchronization synchronization to ensure that notifications can only be sent to registered observers before the message is published to the subject.

Here is the observer's implementation. They will always focus on the subject object.

Copy Code code as follows:

Package com.journaldev.design.observer;

public class Mytopicsubscriber implements Observer {

private String name;
Private Subject topic;

Public Mytopicsubscriber (String nm) {
THIS.NAME=NM;
}
@Override
public void Update () {
String msg = (string) topic.getupdate (this);
if (msg = null) {
System.out.println (name+ ":: No New Message");
}else
System.out.println (name+ ":: Consuming Message::" +msg);
}

@Override
public void Setsubject (Subject sub) {
This.topic=sub;
}

}

Note that the implementation of the update () method uses the GetUpdate () of the viewer to process the updated message. You should avoid passing messages as parameters to the update () method.

To simply test the program to verify the implementation of the topic class.

Copy Code code as follows:

Package com.journaldev.design.observer;

public class Observerpatterntest {

public static void Main (string[] args) {
Create subject
Mytopic topic = new Mytopic ();

Create observers
Observer obj1 = new Mytopicsubscriber ("Obj1");
Observer obj2 = new Mytopicsubscriber ("Obj2");
Observer obj3 = new Mytopicsubscriber ("Obj3");

Register observers to the subject
Topic.register (OBJ1);
Topic.register (OBJ2);
Topic.register (OBJ3);

Attach observer to subject
Obj1.setsubject (topic);
Obj2.setsubject (topic);
Obj3.setsubject (topic);

Check if any update is available
Obj1.update ();

Now send subject
Topic.postmessage ("New message");
}

}

Here is the output:

Copy Code code as follows:

OBJ1:: No New Message
Message Posted to Topic:new message
OBJ1:: Consuming message::new message
OBJ2:: Consuming message::new message
OBJ3:: Consuming message::new message</pre>

UML Diagram of observer pattern

The observer pattern is also called the Publish subscription model. Some of the specific applications in Java are as follows:

The Java.util.EventListener in 1.Swing
2.javax.servlet.http.httpsessionbindinglistener
3.javax.servlet.http.httpsessionattributelistener

The above is the entire observer pattern. I hope you like it already. Share your feelings in the comments, or share them with others.

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.