In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "the realization method of the observer mode of Java". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the realization method of the observer pattern of Java".
The Observer pattern, also known as the publish / subscribe (Publish/Subscribe) pattern, defines an one-to-many dependency between objects, so that whenever an object changes its state, all objects that depend on it are notified and updated automatically.
The Observer is equivalent to the event listener, and the Observable is equivalent to the event source and event, which separates the object of the observer from the observed, and improves the maintainability and reusability of the application. The update of oberver can be triggered by notifying observer when executing logic, and the observed and parameters can be passed at the same time.
Observer Observer: all potential observers must implement the observer interface, which has only the update method, which is called when the subject changes.
Concrete observer ConcreteObserver: a concrete observer can be any class that implements the Observer interface. Observers must register specific topics while receiving updates.
Observer Subject: the topic interface, that is, the observer Observable. Objects use this interface to register as observers or remove themselves from observers. Each topic can have more than one observer.
Concrete observer ConcreteSubject: a specific topic implements the topic interface, and in addition to registration and revocation, the specific topic also implements the notifyObservers () method, which is used to update all observers when the topic state changes. Specific topics may also have ways to set and get status.
Subject includes some observers that need to be notified when their state changes. Therefore, he should provide the observer with a way to register and unregister himself. When the Subject (the observed) changes, you also need to include a method to notify all observers. When notifying the observer, you can push the updated content, or provide another way to get the updated content. Reference: https://www.javacodegeeks.com/2013/08/observer-design-pattern-in-java-example-tutorial.html
JAVA provides a built-in way to implement the observer mode, java.util.Observable and java.util.Observer interfaces. However, they do not use it very widely. Because this implementation is too simple, most of the time we don't want the last extended class to simply implement the observer pattern, because the JAVA class can't inherit much.
UML diagram of observer mode
The Java Messages Service (JMS) messaging service uses observer mode and command mode to publish and subscribe data between different programs. The MVC model-view-control framework also uses the observer pattern, treating the model as the observer and the view as the observer. The view can register itself with the model to get changes to the model.
Observer pattern example
In this example, a simple topic discussion is completed and the observer can register the topic. Any changes caused by the submission of content on this topic will notify all registered observers. Based on the requirements of the Subject observer, this is to implement a basic Subject interface that defines a series of specific methods to be implemented in the concrete class that subsequently implements the interface.
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 ()
/ / method to get updates from subject
Public Object getUpdate (Observer obj)
}
Now create an associated observer. It needs to have a way to attach the Subject to an observer. Another method can accept the change notification from Subject.
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 connection has been established. Now implement the specific theme.
Package com.journaldev.design.observer;import java.util.ArrayList;import java.util.List;public class MyTopic implements Subject {private List 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 observersLocal = null / synchronization is used to make sure any observer registered after message is received is 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 message to the 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 register and unregister observer method is very simple, and the additional method postMessage () will be applied by the client to submit a string message to the topic. Note that the Boolean variable is used to track changes in the state of the subject and notify 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 message to the observer.
It is also important to note that synchronization synchronization is used in notifyObservers () to ensure that notifications can only be sent to registered observers before messages are published to the topic. Here is the implementation of the observer. They will keep an eye on the subject object.
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 observed's getUpdate () to process the updated message. You should avoid passing messages as parameters to the update () method here.
Here is a simple test program to verify the implementation of the topic class.
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 message to subject topic.postMessage ("New Message");}}
Here is the above output:
Obj1:: No new messageMessage Posted to Topic:New MessageObj1:: Consuming message::New MessageObj2:: Consuming message::New MessageObj3:: Consuming message::New Message
The Observer pattern is also known as the publish-subscribe model. Some specific applications in JAVA are as follows:
Swing java.util.EventListenerjavax.servlet.http.HttpSessionBindingListenerjavax.servlet.http.HttpSessionAttributeListener thank you for your reading, the above is the content of "the implementation of the observer mode of Java". After the study of this article, I believe you have a deeper understanding of the implementation of the observer mode of Java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.