Using observer mode to realize communication between components

Source: Internet
Author: User

1. The question was raised

It's often awkward to have an interface before: you want to keep individual components (classes), but you want them to communicate with each other. For example, in Windows Explorer, we want the mouse to click on the left is a tree directory of a node, the right file browsing in time to list the node directory of files and subdirectories, similar to such a simple application, if only one class inherits JFrame, The tree component and the panel that browses the file as members are like:

public class MainFrame extends JFrame
{
   JPanel treePanel;
   JTree tree;
   JPanel filePanel;
   ...
}

This, of course, is easy to pass messages between the two, but the scalability is poor. It is usually easy to think of two ways: to retain members of another component type in one component and to initialize it as a parameter, such as:

class TreePanel extends JPanel
{
   JTree tree;
   ...
}
class FilePanel extends JPanel
{
   public FilePanel(JTree tree){...}
   ...
}

or threading a component, constantly listening to the changes of another component, and then responding accordingly, such as:

class TreePanel extends JPanel
{
   JTree tree;
   ...
}
class FilePanel extends JPanel implements Runnable
{
   public void run()
   {
     while (true)
     {
       //监听tree的变化 
     }
     ...
   }
   ...
}

This is true for our purposes, but the first scenario is obviously not conducive to loose coupling, and the second scenario is a comparison of system resources. By learning Design patterns, we find that we can solve this problem with observer patterns.

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.