Java observable Mode

Source: Internet
Author: User

I. Intention of the observer mode:

When the internal status of an object changes, the external object is automatically notified to respond.

Ii. Composition of the observer mode:

· Observer: internal states may be changed, and external objects must be notified.

· Observer: objects that need to respond to changes in internal states

Iii. JAVA Implementation of the observer mode:

Java APIs provide implementation of the observer mode. The Java. util. observable class and Java. util. Observer interface are used to complete the process.

The former has two important methods:

· Setchanged: Set the internal status to changed

· Notifyobservers (Object OBJ): notifies the observer of changes. The OBJ parameter indicates some changes.

The latter has a core method:

· Update (Object OBJ): changes by the observer. OBJ indicates the information transmitted by the observer. This method is automatically called when policyobservers is called.

The implementation process of the observer mode is as follows:

· Create an observer that inherits java. util. observable

· Create an observer to implement the java. util. Observer Interface

· Registration observation: Call addobserver (Observer observer)

· Call the setchanged () method where the inner state of the object is changed by the observer, and then call the yyobservers (object) method to notify the observer

· The observer's update (object) method responds to changes.

Iv. Benefits of the observer mode:

1. Advantages of the observer mode:

· The observer only needs to know who is observing it, and does not need to know the specific observation details.

· Once an observer changes, the observer only needs to be notified through broadcasting. You do not need to know how the message arrives. This will undoubtedly eliminate the hard coding of communication between the observer and the observer.

· When an observer is observed by multiple observations at the same time, the observer can select only events of interest and ignore other events.

· The combination of multiple observers can form an observation chain. If multiple operations need to be rolled back, the observation chain can play a role at this time.

· The observer can respond to changes of the observed object in real time, such as automatic alarms and interrupted operations.

2. You can use the observer Mode

· Blocking communication between threads: for example, the main thread can be used as the observer between two threads, and the execution thread is the observer. Only the other party exists, but the communication details are unknown.

· Eliminate hard encoding: If there is no observer mode, only the callback mode can be used, or the observer can be called explicitly in the code.

· Optimized exception mechanism: It is particularly suitable for top-level monitoring when exceptions occur, reducing the amount of try-catch code

Code:

 

Public class observable {<br/> private Boolean changed = false; <br/> private vector obs; </P> <p> // create an observer list held by the observer. Note that this list needs to be synchronized. <Br/> Public observable () {<br/> obs = new vector (); <br/>}</P> <p>/** <br/> * Add the observer to the observer list. <br/> */<br/> Public synchronized void addobserver (Observer O) {<br/> If (O = NULL) <br/> throw new nullpointerexception (); <br/> If (! Obs. contains (o) {<br/> obs. addelement (O ); <br/>}</P> <p>/** <br/> * delete an observer <br/> */<br/> Public synchronized void deleteobserver (Observer O) {<br/> obs. removeelement (o); <br/>}</P> <p>/** <br/> * notification operation, that is, the Monitored object changes, notify the corresponding observer to perform preset operations without passing the parameter notification method <br/> */<br/> Public void policyobservers () {<br/> policyobservers (null); <br/>}</P> <p>/** <br/> * different from the preceding notification method, this method accepts a parameter, which is always passed to the observer The observer uses <br/> */<br/> Public void policyobservers (Object Arg) {</P> <p> object [] arrlocal; </P> <p> synchronized (this) {<br/> If (! Changed) <br/> return; <br/> arrlocal = obs. toarray (); <br/> clearchanged (); <br/>}</P> <p> for (INT I = arrlocal. length-1; I> = 0; I --) <br/> (observer) arrlocal [I]). update (this, ARG ); <br/>}< br/> Public interface observer {<br/>/** <br/> * this method is called whenever the observed object is changed. an <br/> * Application Callan <tt> observable </tt> object's <br/> * <code> policyobservers </code> method to have all the objects' S <br/> * Observers notified of the change. <br/> * @ Param o the observable object. <br/> * @ Param Arg an argument passed to the <code> policyobservers </code> <br/> * method. <br/> */<br/> void Update (observable o, object Arg ); <br/>}< br/> public class mailobserver implements observer {</P> <p>/** <br/> * this class is named mailobserver, as the name suggests, she is an observer for sending emails <br/> */<br/> Public void Update (observable o, object Arg) {<br/> system. out. println ("the observer who sent the email has been executed "); <br/>}< br/> public class jmsobserver implements observer {</P> <p> Public void Update (observable o, object Arg) {<br/> system. out. println ("the observer sending the message to the JMS server has been executed "); <br/>}< br/> public class subject extends observable {</P> <p>/** <br/> * business method, once an operation is performed, the observer is notified <br/> */<br/> Public void dobusiness () {<br/> If (true) {<br/> super. setchanged (); <br/>}< br/> policyobservers ("parameters not available now "); <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> // create an observer <br/> subject = new subject (); </P> <p> // create two Observers <br/> observer mailobserver = new mailobserver (); <br/> observer jmsobserver = new jmsobserver (); </P> <p> // Add two observers to the list of observers <br/> subject. addobserver (mailobserver); <br/> subject. addobserver (jmsobserver); </P> <p> // perform business operations <br/> subject. dobusiness (); <br/>}< br/>}

 
The method for using the observer mode in spring is as follows:

<Bean id = "mailobserver" class = "mailobserver"/>

<Bean id = "jmsobserver" class = "jmsobserver"/>

<Bean id = "subjecttarget" class = "subject"/>

<Bean id = "subject"
Class = "org. springframework. Beans. Factory. config. methodinvokingfactorybean">
<Property name = "targetobject"> <ref local = "subjecttarget"/> </property>
<Property name = "targetmethod"> <value> addobserver </value> </property>
<Property name = "arguments">
<List>
<Ref bean = "mailobserver"/>
<Ref bean = "jmsobserver"/>
</List>
</Property>
</Bean>
The observer mode has the following advantages:

(1) The observer mode establishes an abstract coupling between the observer and the observer. What the observer role knows is that a specific observer aggregates, and each specific observer conforms to an abstract observer interface. The observer does not know any specific observer, but only knows that they all have a common interface. Since the observer and observer are not closely coupled, they can belong to different abstract layers.

(2) The observer mode supports broadcast communication. The observer sends a notification to all registered observers.

The observer mode has the following Disadvantages:

(1) It takes a lot of time to notify all observers if they have many direct and indirect observers.

(2) If there is a circular dependency between the observer, the observer will trigger a circular call between them, resulting in system crash. Pay special attention to this when using the observation test mode.

(3) If the notification to the observer is asynchronously delivered through another thread, the system must ensure that the delivery is carried out in an appropriate manner.

(4) Although the observer mode can enable the observer to know the changes of the observed object at any time, the observer mode does not have a mechanism to let the observer know how the observed object changes.

 

 

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.