Details of Java design pattern (III): Observer __java

Source: Internet
Author: User

The observer pattern, also called the (publish-subscribe) pattern, is a type of behavioral pattern that defines a one-to-many relationship, which is handled when multiple observers simultaneously monitor the changes that occur to the observed.

No more nonsense, today to share about the Observer mode related content. No more nonsense, then go directly to the code instance.


Observer interface:


/** *
 Observer Interface
 * @author lyr
 * @date November 27, 2017 * * Public
interface Observer {
	
	void update ( Observable o);
}

Observed by:

public class ConcreateObserver1 implements observer{public

	void update (observable o) {
		System.out.println (" Observer 1 found "+o.getclass ()" Getsimplename () + "Change!");
		SYSTEM.OUT.PRINTLN ("Observer 1 responds ...");
	}


public class ConcreateObserver2 implements observer{public

	void update (observable o) {
		System.out.println (" Observer 2 Found "+o.getclass ()" Getsimplename () + "Change!");
		SYSTEM.OUT.PRINTLN ("Observer 2 responds ...");
	}




Specific actions:

public class Observable {

	list<observer> observers = new arraylist<observer> ();
	
	public void Addobserver (Observer o) {
		observers.add (o);
	}
	
	public void Change () {
		System.out.println ("I am the observed, I have changed!");
		Notifyobservers ();
	}
	
	public void Notifyobservers () {to
		(Observer obs:observers) {
			obs.update (this);
		}
	}
}

Test

public class Client {public

	static void Main (string[] args) {
		observable obsable = new observable ();
		Obsable.addobserver (New ConcreateObserver1 ());
		Obsable.addobserver (New ConcreateObserver2 ());
		Obsable.change ();
	}



Here's the test results.


Although the above code is low, it is sufficient to explain the problem. It is clear from the steps above that when the observed changes, it informs the other observers that when the observer catches the notice from the Observer, it will be dealt with accordingly according to their own needs. Note, however, that these classes are custom classes, not related classes in the JDK, so be aware of the distinction.

What's more, the observer pattern separates the observer and the observer from the responsibilities of the observers, allowing them to maintain their own functional module areas, thereby improving the reusability and maintainability of the system.


Java built in observer mode

In the Java.util package, contains the basic observer interface and observable abstract class, in terms of use in addition to the implementation of the above features are registered, delete, etc., and notify the observer of those features have been built.

Let's take a look at the viewer interface:


Observer interface, each observer must implement this interface public
interface Observer {
    //This method is the observer's response action when observing the object's changes, passing in the observed object and a reservation parameter
    void update (Observable o, Object arg);
}


And the following are the observed classes:


Import Java.util.Vector;
    The Observer class public class observable {//This is a change identifier to mark whether the observed person has changed the private Boolean changed = FALSE;
    
    Hold an observer list private Vector OBS;
    Public observable () {obs = new Vector (); //Add observer, add to synchronized void Addobserver (Observer o) {if (o = = null) throw new N
        Ullpointerexception ();
          if (!obs.contains (o)) {obs.addelement (o);
    }//delete observer public synchronized void Deleteobserver (Observer o) {obs.removeelement (o);
    The overloaded method of//notifyobservers (Object Arg) is public void Notifyobservers () {notifyobservers (null);
    //Notify all observers that the observer has changed and that you can execute your Update method.
        A temporary array of public void Notifyobservers (Object arg) {//, which is used to keep the current state of the observer list while accessing the observer, is actually a design pattern, a memo pattern.
    Object[] arrlocal;
        Note this synchronization block, which means that the object is locked when the viewer list is fetched. That is, before I get to the Observer list, no other threads are allowed to change the viewer list synchronized (this) {///If no change is returned directly
if (!changed)                Return
            This places the current observer list into a temporary array arrlocal = Obs.toarray ();
        Reset the change identity back to the unchanged clearchanged (); }//Note that the For loop is not in the sync block, at which point the lock of the Observer has been released, and other threads can change the list of observers//But this does not affect what we are doing now, because we have copied the Observer list to the TEMP array//We will only notify The observer in the array, the current deletion and addition of the observer, will not affect the object we are notifying for (int i = arrlocal.length-1 i>=0; i--) ((Observer) arrlocal[i]).
    Update (this, ARG);
    //Delete all observers public synchronized void Deleteobservers () {obs.removeallelements ();
    }//Logo The Observer has been changed protected synchronized void setchanged () {changed = TRUE;
    //Logo The observer did not change protected synchronized void clearchanged () {changed = FALSE;
    //Returns whether the observed person has changed the public synchronized Boolean haschanged () {return changed;
    //Returns the number of observers public synchronized int Countobservers () {return obs.size (); }
}


One thing to note when using Java's built-in observer model is to notifyobservers a piece of code in this method:

for (int i = arrlocal.length-1 i>=0; i--)
            ((Observer) arrlocal[i]). Update (this, ARG);

You will find that when there is an exception in the update process, other observers since then have received no notification, the question I was referring to when I was looking at a predecessor introducing the Observer model, and I reckon that Sun should take this into consideration, but it does not seem to be dealing with him now. So under normal circumstances, when I find this problem, I usually wrap this method with a Try...catch statement block, which is as shown in the following code:


for (int i = arrlocal.length-1; i>=0; i--) {
        try {
		((Observer) arrlocal[i]). Update (this, arg);
	} catch ( Exception e) {
		e.printstacktrace ();
	}
}

After this process, if there is a problem, it will not affect the status of the subsequent observers to update.

Of course, you said that in addition to the observer model no other problem is impossible, in general it should be a design problem, after all, the observer and the Observer is a one-to-many relationship, if the reverse can not be used. Furthermore, each observer has to implement the observer interface to be added to the list of the observers. If an observer already exists and cannot change its code, then there is no way to be a true observer, but the problem can be handled through the adapter pattern.

This time the sharing will be here, the next one bye!

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.