Use the observer mode to solve inter-component communication problems

Source: Internet
Author: User

Http://www.35java.com/zhibo/forum.php? MoD = viewthread & tid = 258 & extra = Page % 3d2

Question proposal In the past, when I made an interface, I often encountered such an embarrassing situation: I want to keep all the independent components (classes), but I want them to communicate with each other. For example, in Windows Explorer, we want to click a node in the tree directory on the left. The file browsing on the right can list the files and subdirectories under the node directory in a timely manner, similar to such a simple application, if only one class inherits jframe, and the tree component and the Panel of the browser file act as a member, it is like:

Public
ClassMainframe extends jframe
{
Jpanel treepanel;
Jtree tree;
Jpanel filepanel;
...
}

it is easy to transmit messages between the two, but the scalability is poor. There are two methods to keep a member of the other component type in one component and pass in the reference as a parameter during initialization. For example:
class treepanel extends jpanel
... {< br> jtree;
...
}

class filepanel extends jpanel
... {< br> Public filepanel (jtree tree) ... {...}
...
}

Or thread one component, constantly listen to the changes of another component, and then make the corresponding reflection, such:
ClassTreepanel extends jpanel
{
Jtree tree;
...
}

ClassFilepanel extends jpanel implements runnable
{
Public
VoidRun ()
{
While(True)
{
//Monitor tree changes
}
...
}
...
}

This can indeed achieve our goal, but the first scheme is obviously not conducive to loose coupling, and the second scheme occupies system resources. By studying the design mode, we found that the observer mode can be used to solve this problem.

Observer Mode
The design patterns include creation, structure, and behavior. The behavior pattern specifically processes communication between objects and specifies the interaction mode. The observer pattern is a behavior pattern. According to the definition of Gang of Four in design patterns, the observer mode defines a one-to-many dependency between objects, when the status of an object changes, all objects dependent on it are notified and automatically updated. This description is exactly in line with our requirements for the "component communication" issue. Let's first look at the structure of the observer mode:

The meanings of each element are as follows:
Subject: The abstract interface of the observed object. It provides registration and cancellation services for the Observer (observer), and the notify method notifies the observer object to change;
Object: the abstract interface of the observer. The update method is the action to be taken after the subject state changes are notified;
Concretesubject: Implementation of subject;
Concreteobserver: Implementation of the observer
The observer mode is very useful when implementing the MVC structure and is decoupled from data representation.

Observer mode in Java: observer and observable
After learning about the description of the observer mode, we are more concerned about how it is applied in Java. Fortunately, since JDK 1.0, there has been an API dedicated to processing such applications. This is the observer interface and the observable class, which are part of the Java. util package. It seems that Java developers are really familiar with the essence of the design model, and Java is indeed born for real object-oriented, huh, huh!
Here, the observer and observable correspond to the observer and subject in the design mode respectively. The traces of the methods they define are quite obvious:
Observer method:
Update (observable subject, object Arg) monitors subject. When the status of the subject object changes, what will the observer respond to? Arg is the parameter passed to the notifyobservers method of observable;
Observable method:
Addobserver (Observer observer) Observer registers itself with this subject
Haschanged () check whether the subject status has changed
Setchanged () sets the subject status to "changed"
Notifyobservers () notifies observer that the subject status has changed

Application of observer mode in Java GUI event model
In fact, several design patterns are used in the AWT/swing event model. The previous JDK 1.0 AWT used the "inherited event model ", the component class of this model defines a series of event processing methods, such as handleevent, mousedown, and mouseup, our response to an event is implemented by inheriting component classes and overwriting corresponding event handling methods. This model has many disadvantages and should not be handled by the event handler, in addition, according to the principles in the book "design patterns", "inheritance" is generally considered to be a "destruction of encapsulation", and close coupling between parent and child classes reduces flexibility, at the same time, inheritance easily leads to a huge family tree scale, which is not conducive to Component reuse.
After JDK 1.1, the new event model is "Authorization-based event model", which is the listener model we are familiar with now. event processing is no longer the responsibility of the event-generating object, the listener is responsible for this. The observer mode is used to design the MVC structure in swing components. As we all know, MVC represents "Model-View-controller", that is, "data-represents logic-operation ", data can correspond to multiple representations, so that the view is in the observer status, while the model is subject.

Simple Example
Back to the example of the Explorer at the beginning of this article, we will consider creating a simple image browser to make the Tree Selection Component and Image Browsing panel in two different classes, the Image Browsing panel displays the corresponding image based on the node of the selected tree. Therefore, the Image Browsing panel is an observer and the tree is subject. Due to the single inheritance of Java, we cannot inherit jpanel and observable at the same time, but we can use a combination of objects to put a subject into our class, and trigger the setchanged method of subject through treeselectionlistener, the notifyobservers method is used to notify the observer.
Example Code As follows:
// Leftpanel. Java
Package com. jungleford. test;
Import java. AWT. borderlayout;
Import javax. Swing.
* ;
Import javax. Swing.
Event . Treeselectionlistener;
Import javax. Swing.
Event . Treeselectionevent;
Import javax. Swing. Tree. defaultmutabletreenode;
Import java. util. observable;
Import java. util. observer;

Public Final Class Leftpanel extends jpanel
{
// Layout Tree Selection view on the left

PrivateJtree tree;//Tree Selection View

PrivateJscrollpane scroll;//Make the view scroll

PrivateDefaultmutabletreenode root, node1, node2;//Root Node and two leaves

PrivateSensor sensor;//Sensor is an observable. as it can only be inherited by a single user, it acts as a composite member.

PrivateString file;//Image File name, content that communicates with rightpanel

Public Leftpanel (Observer observer)
{
File
=
"" ;
Sensor
=
New Sensor ();
Sensor. addobserver (observer );
// Register observer with observable
Root =
New Defaultmutabletreenode ( " Images " );
Tree
=
New Jtree (Root );
Node1
=
New Defaultmutabletreenode ( " Rabbit " );
Node2
=
New Defaultmutabletreenode ( " Devastator " );
Root. Add (node1 );
Root. Add (node2 );
Tree. addtreeselectionlistener (
New Treeselectionlistener ()
{
// Tree node selection action

Public
void valuechanged (treeselectionevent E)
{< br> Object OBJ
= E. getpath (). getlastpathcomponent ();
If (OBJ instanceof defaultmutabletreenode)
{< br> defaultmutabletreenode node
= (defaultmutabletreenode) OBJ;
If (node = root)
file
=
" ; /// select root

If(Node=Node1)
File
=
"Rabbit.jpg";//Select node1

If (Node = Node2)
File
=
" Devastator.gif " ; // Select node2
Sensor. setdata (File ); // Change observable
Sensor. policyobservers (); // Notification observer, object changed
}
}
});
Scroll
=
New Jscrollpane (tree );
Add (scroll, borderlayout. center );
}

Public Observable getsensor ()
{
// Returns the observable object so that the observer can obtain

ReturnSensor;
}
}

ClassSensor extends observable
{
//Define your own Observable

Private Object Data;

Public
Void Setdata (Object newdata)
{
Data
= Newdata;
Setchanged ();
// Change observable
System. Out . Println ( " Data changed! " );
}

Public Object getdata ()
{
Return Data;
}
}

// Rightpanel. Java
Package com. jungleford. test;
Import java. AWT.
* ;
Import javax. Swing. jpanel;
Import java. util. observer;
Import java. util. observable;

Public
Class Rightpanel extends jpanel implements observer
{
// Layout the Image Browsing view on the right

Private Image image;

Public
Void Update (observable subject, object OBJ)
{
// Define the response action after an observable change is received
String File = (String) (sensor) subject). getdata ();
If ( ! File. Equals ( "" ))
{
Image
= Toolkit. getdefatooltoolkit (). getimage (File );
Mediatracker Tracker
=
New Mediatracker ( This ); // Define image tracking
Tracker. addimage (image, 0 );
Try
{
Tracker. waitforid (
0 ); // Wait until the image is fully loaded
}
Catch (Interruptedexception E)
{
E. printstacktrace ();
}
}
Else
Image
=
Null ;
Repaint ();
// Redraw component
}

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.