Java Observer design pattern (observable and observer) _java

Source: Internet
Author: User
Tags int size

The Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to one subject object at the same time.

When the subject object changes in state, all the observer objects are notified so that they can automatically update themselves.

I. Introduction to the Observer model

In Java, the Observer pattern is implemented through the observable class and the Observer interface. A observer object monitors the change of a observable object, and when the observable object changes, observer is notified and can work accordingly.

If screen A is a display of data in the database, and the picture B modifies the data in the database, then the screen a will be back to load. Then you can use the Observer mode.

Second, the Observer Mode implementation method

There are two methods in java.util.Observable that are particularly important for observer.

①setchanged () method

/** * Sets The changed flag for this {@code observable}. 
After calling * {@code setchanged ()}, {@code haschanged ()} to return {@code true}. 
*/protected void setchanged () {changed = TRUE; }②notifyobservers () method/Notifyobservers (Object data) method [Java] View plaincopy/** * If {@code haschanged ()} returns {@co De true}, calls the {@code update ()} * method for every observer in the list of observers using NULL as the * argument. 
Afterwards, calls {@code clearchanged ()}. 
* <p> * equivalent to calling {@code notifyobservers (null)}. 
*/public void Notifyobservers () {notifyobservers (null); }/** * If {@code haschanged ()} returns {@code true}, calls the {@code update ()} * method for every Observer in the LIS T of observers using the specified * argument. 
Afterwards calls {@code clearchanged ()}. 
* * @param data * The argument passed to {@code update ()}. 
* * @SuppressWarnings ("unchecked") public void Notifyobservers (Object data) {int size = 0; Observer[] Arrays = null; 
Synchronized (this) {if (haschanged ()) {clearchanged (); 
Size = Observers.size (); 
arrays = new Observer[size]; 
Observers.toarray (arrays); 
} if (arrays!= null) {for (Observer observer:arrays) {observer.update (this, data);  } 
} 
}

The above two methods are very important

Setchanged () Method--

Used to set an internal flag bit indicating that the data has changed
Notifyobservers () method/Notifyobservers (Object Data) Method--
Notifies all observer that the data has changed, when all the observer automatically invokes the modified update (observable observable, Object data) method to do some processing (such as updating the screen data).
We can see that the notification Observer has two methods, one with no parameters and one with a parameter. So what's the effect of this parameter?
One of the roles: now I don't want to notify all the observer, but just one of the specified observer do some processing, then you can pass a parameter as ID, and then in all the observer to judge, Each observer judge only receives the end parameter ID is belong to its own only to do some processing.

Of course the parameters have other functions, I just cite an example.

Here's an example to illustrate:

Import java.util.Observable; 
/** 
* Observed class/public 
class Simpleobservable extends observable 
{ 
private int data = 0; 
public int GetData () {return 
data; 
} 
public void SetData (int i) { 
if (this.data!= i) { 
this.data = i; 
Setchanged (); 
Only after Setchange () is called, Notifyobservers () calls update (), otherwise nothing is done. 
notifyobservers (); 
} 
 

The above class is an observer class that inherits the observable class, indicating that the class can be observed.
Then in the SetData () method, where the data is changed, the Setchanged () method and the Notifyobservers () method of the observable class are invoked to indicate that the data has changed and notify all observer to call their update () method to do some processing.

Note: Only after the Setchange () is called, Notifyobservers () will call Update (), or nothing.

/** 
* Observer class * * Public 
class Simpleobserver implements Observer 
{public 
simpleobserver ( Simpleobservable simpleobservable) { 
simpleobservable.addobserver (this); 
} 

public void update (observable observable, object data) {//data is any object that is used to pass parameters 
System.out.println ("Data has changed to "+ (simpleobservable) observable.getdata ()); 
} 

By generating an instance of the Observer (Simpleobservable Class), the Addobserver (this) method is invoked to let the Observer (Simpleobserver Class) Achieve the purpose of observing the observed (Simpleobservable Class).
Then you have to make a copy of the update () method to do some processing after the data change.

You can write a simple test class to test

public class SimpleTest 
{public 
static void Main (string[] args) { 
simpleobservable doc = new Simpleobservable (); 
Simpleobserver view = new Simpleobserver (DOC); 
Doc.setdata (1); 
Doc.setdata (2); 
Doc.setdata (2); 
Doc.setdata (3); 
} 
} 

The results of the operation are as follows

Data has changed to 1
Data has changed to 2//second SetData (2) The update was not invoked because there was no setchange
Data has changed to 3

Here are some other properties and methods for a observable class

Properties--

Observers is a list that holds all the observer to be notified.
List<observer> observers = new arraylist<observer> ();
Changed is a Boolean flag bit that indicates whether the data has changed.
Boolean changed = FALSE;

Method-

Add a Observer to list observers public void Addobserver (Observer Observer) {if (Observer = null) {throw new Nullpointe 
Rexception (); 
} synchronized (this) {if (!observers.contains (Observer)) OBSERVERS.ADD (Observer); ///Remove a Observer public synchronized void Deleteobserver (Observer Observer) {Observers.remove (observe) from list observers 
R); 
//Empty list observers public synchronized void Deleteobservers () {observers.clear (); 
}//Returns the number of observer in the list observers public int countobservers () {return observers.size (); 
//Reset data change flag bit to unchanged protected void clearchanged () {changed = FALSE; 
//Change the data marker bit to change protected void setchanged () {changed = TRUE; 
}//Judge the value of the flag bit public boolean haschanged () {return changed; 
//Notifies all observer (no parameter) public void Notifyobservers () {notifyobservers (null); 
//Notifies all observer (with parameters) @SuppressWarnings ("unchecked") public void Notifyobservers (Object data) {int size = 0; 
observer[] arrays = null; 
Synchronized (this) {if (haschanged ()) {Clearchanged (); 
Size = Observers.size (); 
arrays = new Observer[size]; 
Observers.toarray (arrays); 
} if (arrays!= null) {for (Observer observer:arrays) {observer.update (this, data);  } 
} 
}

Note: Be sure to remove the Observer object from the list with Deleteobserver before it is destroyed, that is, call the Deleteobserver () method in the OnDestroy () method.

Otherwise, because of the relationship of the object reference, the Observer object will not be garbage collected, causing a memory leak, and the dead observer will still be notified, may cause unexpected errors, and as the list becomes larger, the notifyobservers operation will become slower.

 The actors involved in the Observer pattern are:

Abstract theme (Subject) role: Abstract theme Roles Keep all references to observer objects in a cluster (such as a ArrayList object), each subject can have any number of observers. Abstract topics provide an interface for adding and removing observer objects, and abstract theme roles are also called abstract-observer (observable) roles.

Specific theme (ConcreteSubject) role: The state is deposited in a specific observer object, and all registered observers are notified when the internal state of the specific subject changes. The specific theme role is also called the specific Observer (concrete observable) role.

Abstract observer (OBSERVER) role: Defines an interface for all specific observers and updates itself when a topic is notified, an interface called an update interface.

The specific observer (CONCRETEOBSERVER) role: The State of the store and the topic itself. The specific observer role implements the update interface required by the abstract observer role to coordinate itself with the state of the subject. The specific observer role can maintain a reference to a specific subject object, if necessary.

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.