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.