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--
Today, I will talk to you about the role of the observer mode of JAVA, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
The Observer pattern (Observer Pattern) is used when there is an one-to-many relationship between objects. For example, when an object is modified, its dependent objects are automatically notified. The observer model belongs to the behavioral model. Observer pattern is a very important design pattern in Java.
The roles involved in the observer model are:
● Abstract topic (Subject) roles: abstract topic roles store all references to observer objects in an aggregation (such as an ArrayList object), and each topic can have any number of observers. Abstract topics provide an interface to add and delete observer objects. Abstract topic roles are also called abstract Observable roles.
● specific topic (ConcreteSubject) role: stores the relevant state in a specific observer object; notifies all registered observers when the internal state of a specific topic changes. The specific subject role is also called the specific Concrete Observable role.
● Abstract Observer (Observer) role: define an interface for all concrete observers to update themselves when notified of the topic. This interface is called the update interface.
● specific observer (ConcreteObserver) role: stores a state that is consistent with the state of the topic. The concrete observer role implements the update interface required by the abstract observer role in order to coordinate its own state with that of the subject. If necessary, the specific observer role can maintain a reference to a specific subject object.
Abstract theme (subject) roles:
Import java.util.ArrayList;import java.util.List;public abstract class Subject {private Listlist = new ArrayList (); public void register (MyObserver myObserver) {if (! list.contains (myObserver)) {list.add (myObserver);}} public void remove (MyObserver myObserver) {if (list.contains (myObserver)) {list.remove (myObserver) }} public void notifyObserver () {for (MyObserver myObserver: list) {myObserver.update ();}
Abstract observer role:
Public interface MyObserver {void update ();}
Specific subject roles:
Public class Repoter extends Subject {private String msg; public String getMsg () {return msg;} public void setMsg (String msg) {this.msg = msg; if (change ()) {notifyObserver ();}} public Boolean change () {if (msg.equals (getMsg () {return true } else {return false;}
The first specific observer:
Public class PeopleDaily implements MyObserver {private Subject subject; public PeopleDaily (Subject subject) {this.subject = subject; subject.register (this);} @ Override public void update () {System.out.println ("People's Daily released the latest report:" + ((Repoter) subject). GetMsg ());} public void remove () {subject.remove (this);}}
The second specific observer:
Public class NewsFeeds implements MyObserver {private Subject subject; public NewsFeeds (Subject subject) {this.subject = subject; subject.register (this);} @ Override public void update () {System.out.println ("News released the latest report:" + ((Repoter) subject). GetMsg ());} public void remove () {subject.remove (this);}}
The third specific observer:
Public class XinHuaNewsAgency implements MyObserver {private Subject subject; public XinHuaNewsAgency (Subject subject) {this.subject = subject; subject.register (this);} @ Override public void update () {System.out.println ("Xinhua News Agency released the latest report:" + ((Repoter) subject). GetMsg ());} public void remove () {subject.remove (this);}}
Test:
Public class TestDemo {@ Test public void demo () {Repoter repoter = new Repoter (); NewsFeeds newsFeeds = new NewsFeeds (repoter); XinHuaNewsAgency xinHuaNewsAgency = new XinHuaNewsAgency (repoter); PeopleDaily peopleDaily = new PeopleDaily (repoter); repoter.setMsg ("strive for the great rejuvenation of the Chinese nation!") ;}}
Results:
News broadcast released the latest report: strive for the great rejuvenation of the Chinese nation! Xinhua News Agency released the latest report: strive for the great rejuvenation of the Chinese nation! People's Daily released the latest report: strive for the great rejuvenation of the Chinese nation! Process finished with exit code 0
Delete an observer and try again:
Public class TestDemo {@ Test public void demo () {Repoter repoter = new Repoter (); NewsFeeds newsFeeds = new NewsFeeds (repoter); XinHuaNewsAgency xinHuaNewsAgency = new XinHuaNewsAgency (repoter); PeopleDaily peopleDaily = new PeopleDaily (repoter); repoter.setMsg ("strive for the great rejuvenation of the Chinese nation!") ; repoter.remove (xinHuaNewsAgency); System.out.println ("- -"); repoter.setMsg ("Huawei releases the latest flagship Mate30 series models");}}
Results:
News broadcast released the latest report: strive for the great rejuvenation of the Chinese nation! Xinhua News Agency released the latest report: strive for the great rejuvenation of the Chinese nation! People's Daily released the latest report: strive for the great rejuvenation of the Chinese nation! -News broadcast released the latest report: Huawei released the latest flagship Mate30 series model mobile phone People's Daily released the latest report: Huawei released the latest flagship Mate30 series model mobile phone Process finished with exit code 0
For the observer mode, JDK has provided us with corresponding interfaces and classes.
JDK source code:
Package java.util;/** when a class wants to be informed of changes in observable objects, it can implement the Observer interface. * @ author Chris Warth * @ see java.util.Observable * @ since JDK1.0 * / public interface Observer {/ * * this method is called whenever the observation object changes. The application calls the notifyObservers method of the Observable object so that all observers of the image are notified of the change. * @ param o the observable object. * @ param arg an argument passed to the notifyObservers * method. * / void update (Observable o, Object arg);}
Observer is an interface, but a method update is used to receive the notification from the notifier and make a response. The specific logic must be implemented by the developer himself.
For the observed, the source code of JDK is as follows:
The package java.util;/** class represents observable objects, or "data" in the model-view paradigm. It can be subclassed to represent the objects that the application wants to observe. * an observable object can have one or more observers. The observer can be any object that implements the interface Observer. * after the observable instance changes, the notifyObservers method of Observable is called, and the application notifies all observers of the change by calling update. * the delivery order of notifications is not specified. The default implementations provided in the Observable class will notify Observers in the order in which they are registered, but subclasses may change this order, send notifications on separate threads using the unguaranteed order, or can guarantee that their subclasses follow this order because they choose. * Note that this notification mechanism is independent of threads and is completely separate from Object-like wait and notify mechanisms. * when a new observable object is created, its observer collection is empty. The two observers are considered the same if and only if the equals method returns true for them. * @ author Chris Warth * @ see java.util.Observable#notifyObservers () * @ see java.util.Observable#notifyObservers (java.lang.Object) * @ see java.util.Observer * @ see java.util.Observer#update (java.util.Observable, java.lang.Object) * @ since JDK1.0 * / public class Observable {private boolean changed = false; private Vector obs / / the constructor public Observable () {obs = new Vector ();} / * * adds an observer to the observer set of this object, provided that it is different from an existing observer in the collection. The order in which notifications are sent to multiple observers is not specified. * @ param o an observer to be added. * @ throws NullPointerException if the parameter o is null. * / public synchronized void addObserver (Observer o) {if (o = = null) throw new NullPointerException (); if (! obs.contains (o)) {obs.addElement (o);}} / * * removes the observer from the observer set of the object. Passing null to this method will not work. * @ param o the observer to be deleted. * / public synchronized void deleteObserver (Observer o) {obs.removeElement (o);} / * * if the object has changed, as shown in the hasChanged method, notify all its observers, and then call the clearChanged method to indicate that the object is no longer * changed. * each observer calls the update method with two parameters: the observable object and null. In other words, this method is equivalent to: * notifyObservers (null) * @ see java.util.Observable#clearChanged () * @ see java.util.Observable#hasChanged () * @ see java.util.Observer#update (java.util.Observable, java.lang.Object) * / public void notifyObservers () {notifyObservers (null) } / * * if the object has changed, as shown in the hasChanged method, notify all its observers, and then call the clearChanged method to indicate that the object is no longer * changed. * each observer calls the update method with two parameters: the observable object and the arg parameter. * @ param arg any object. The * @ see java.util.Observable#clearChanged () * @ see java.util.Observable#hasChanged () * @ see java.util.Observer#update (java.util.Observable, java.lang.Object) * / public void notifyObservers (Object arg) {/ * temporary array buffer is used as a snapshot of the current Observers state. * / Object [] arrLocal; synchronized (this) {/ * * We do not want Observer to make callbacks to arbitrary code when it has its own Monitor. We extract the coexistence of each Observable from the Vector * the code that stores the Observer state needs to be synchronized, but notifies the observer that it will not (should not). The worst outcome of any potential competitive conditions here is: * 1) newly added observers will miss ongoing notifications * 2) recently unregistered observers will be incorrectly notified * / if (! changed) return; arrLocal = obs.toArray (); clearChanged () } for (int I = arrLocal.length-1; I > = 0; iMury -) ((Observer) arrLocal.update (this, arg);} / * * clears the list of observers so that the object no longer has any observers. * / public synchronized void deleteObservers () {obs.removeAllElements ();} / * marks this Observable object as changed; the hasChanged method will now return true. * / protected synchronized void setChanged () {changed = true;} / * * indicates that the object has not changed or that all its observers have been notified of its recent changes, so the hasChanged method will now return false. * this method is called automatically by the notifyObservers method. * @ see java.util.Observable#notifyObservers () * @ see java.util.Observable#notifyObservers (java.lang.Object) * / protected synchronized void clearChanged () {changed = false;} / * * test whether this object has changed. * @ return true if and only if the setChanged * method has been called more recently than the * clearChanged method on this object; * false otherwise. * @ see java.util.Observable#clearChanged () * @ see java.util.Observable#setChanged () * / public synchronized boolean hasChanged () {return changed;} / * * returns the number of observers for this Observable object. * @ return the number of observers of this object. * / public synchronized int countObservers () {return obs.size ();}}
Java source code uses Vector,Vector, which is thread-safe compared to ArrayList. The synchronized keyword is used for both methods when adding and removing observers, both for multithreading.
Observer: implement the observer interface (java.util.Observer), then call the addObserver () method of any Observable object, and call the deleteObserver () method when you log out of the observer.
The first observer:
Public class XinhuaNewsAgency implements Observer {/ / observed object private Observable observable; public XinhuaNewsAgency (Observable observable) {this.observable = observable; / / add the observer object to the observer collection observable.addObserver (this) } @ Override public void update (Observable o, Object arg) {if (o instanceof Repoter) {System.out.println ("Xinhua News Agency released the latest report:" + ((Repoter) o) .getMsg ());}} public void remove () {/ / delete observer observable.deleteObserver (this);}}
The second observer object:
Public class PeopleDaily implements Observer {/ / observed object private Observable observable; public PeopleDaily (Observable observable) {this.observable = observable; / / add the observer object to the observer collection observable.addObserver (this) } @ Override public void update (Observable o, Object arg) {if (o instanceof Repoter) {System.out.println ("People's Daily released the latest report:" + ((Repoter) o) .getMsg ());}} public void remove () {/ / delete observer observable.deleteObserver (this);}}
The third observer:
Public class NewsFeeds implements Observer {/ / observed object private Observable observable; public NewsFeeds (Observable observable) {this.observable = observable; / / add the observer object to the observer collection observable.addObserver (this) } @ Override public void update (Observable o, Object arg) {if (o instanceof Repoter) {System.out.println ("News released the latest report:" + ((Repoter) o). GetMsg ());}} public void remove () {/ / delete observer observable.deleteObserver (this);}}
The observed: inherits the java.util.Observable class, calls the setChanged () method, and marks the state change. Then call the nofityObservers () method or the notifyobservers (Object arg) method.
Public class Repoter extends Observable {private String msg; public String getMsg () {return msg;} public void setMsg (String msg) {this.msg = msg; this.setChanged (); this.notifyObservers (msg);}}
Test:
Public class TestDemo {@ Test public void demo () {Repoter repoter = new Repoter (); NewsFeeds newsFeeds = new NewsFeeds (repoter); PeopleDaily peopleDaily = new PeopleDaily (repoter); XinhuaNewsAgency xinhuaNewsAgency = new XinhuaNewsAgency (repoter); repoter.setMsg ("strive for the great rejuvenation of the Chinese nation!") ;}}
Results:
Xinhua News Agency released the latest report: strive for the great rejuvenation of the Chinese nation! People's Daily released the latest report: strive for the great rejuvenation of the Chinese nation! News broadcast released the latest report: strive for the great rejuvenation of the Chinese nation! Process finished with exit code 0
It is found that the order is not consistent with the order of registration. Log off the news webcast and run:
Public class TestDemo {@ Test public void demo () {Repoter repoter = new Repoter (); NewsFeeds newsFeeds = new NewsFeeds (repoter); PeopleDaily peopleDaily = new PeopleDaily (repoter); XinhuaNewsAgency xinhuaNewsAgency = new XinhuaNewsAgency (repoter); repoter.setMsg ("strive for the great rejuvenation of the Chinese nation!") ; newsFeeds.remove (); System.out.println ("- -"); repoter.setMsg ("Huawei releases the latest flagship Mate30 series models");}}
Results:
Xinhua News Agency released the latest report: strive for the great rejuvenation of the Chinese nation! People's Daily released the latest report: strive for the great rejuvenation of the Chinese nation! News broadcast released the latest report: strive for the great rejuvenation of the Chinese nation! -Xinhua News Agency released the latest report: Huawei released the latest flagship Mate30 series model mobile phone People's Daily released the latest report: Huawei released the latest flagship Mate30 series model mobile phone Process finished with exit code 0
Disadvantages:
Observable is a class, not an interface, resulting in the low extensibility of the Observable class, which is not as flexible as the observer pattern you implement.
Observable protects some methods (setChanged () and clearChanged () are protected), which means that there will be critical methods that cannot be called unless they inherit from Observable. Makes it impossible for other classes to get the functionality of the Observable class in a combined way.
After reading the above, do you have any further understanding of the role of JAVA's observer mode? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
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.