您要实现的“什么”问题将推动“如何”发展。
例如…
您可以在第一帧中保持对第二帧的引用,并在单击按钮时告诉第二帧发生了更改。
public class Firstframe extends Jframe { // Reference to the second frame... // You will need to ensure that this is assigned correctly... private Secondframe secondframe; // The text field... private JTextField textField; // The action handler for the button... public class ButtonActionHandler implements ActionListener { public void actionPerformed(ActionEvent evt) { secondframe.setLabelText(textField.getText()); } }}问题是它暴露了
Secondframe第一个,使它可以对它做一些讨厌的事情,例如删除所有组件。
更好的解决方案是提供一系列接口,使两个类可以相互交谈…
public interface TextWrangler { public void addActionListener(ActionListener listener); public void removeActionListener(ActionListener listener); public String getText();}public class Firstframe extends Jframe implements TextWrangler { private JButton textButton; private JTextField textField; public void addActionListener(ActionListener listener) { textButton.addActionListener(listener); } public void removeActionListener(ActionListener listener) { textButton.removeActionListener(listener); } public String getText() { return textField.getText(); }}public class Secondframe extends Jframe { private JLabel textLabel; private JTextField textField; private TextWrangler textWrangler; public Secondframe(TextWrangler wrangler) { textWrangler = wrangler; wrangler.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { textLabel.setText(textWrangler.getText()); } }); }}这基本上限制了
Secondframe实际可以访问的内容。尽管可以争论的是
ActionListener,该组织
Secondframe可以使用
ActionEvent源来查找更多信息,但从本质上讲,这是一种不可靠的机制,因为
interface没有提及应如何实施…
这是观察者模式的基本示例



