我目前正在用 Java 编写一个 Blackjack 应用程序,它需要用 MVC 架构编写。我的所有模型、视图和控制器都已完全编码,并且一切正常。但是,我想知道将侦听器附加到组件的最佳方式是什么(例如,JButton)。
我当前的设计将视图中需要侦听器的所有组件声明为 public final。然后它将视图传递给控制器。从那里,控制器可以完全控制访问组件并添加动作侦听器。代码示例:
public class View extends JFrame {
public final JButton myBtn1 = new JButton("Button 1");
public final JButton myBtn2 = new JButton("Button 2");
public View() {
//constructor code here....
}
}
public class Controller {
private Model myModel;
private View myView;
public Controller(Model m, View v) {
myModel = m;
myView = v;
//now add listeners to components...
myView.myBtn1.addActionListener(new MyActionListener1());
myView.myBtn2.addActionListener(new MyActionListener2());
}
}
但是,我的一个朋友已经将他所有的 JButton 声明为私有范围,然后在视图中创建了公共方法以将动作侦听器添加到各自的组件中。对我来说,这似乎是浪费时间,只会添加不必要的代码。代码示例:
public class View extends JFrame {
private JButton myBtn1 = new JButton("Button 1");
private JButton myBtn2 = new JButton("Button 2");
public View() {
//constructor code here....
}
public void myBtn1AddActionListener(ActionListener a) {
myBtn1.addActionListener(a);
}
public void myBtn2AddActionListener(ActionListener a) {
myBtn2.addActionListener(a);
}
//etc etc...
}
public class Controller {
private Model myModel;
private View myView;
public Controller(Model m, View v) {
myModel = m;
myView = v;
//now add listeners to components...
myView.myBtn1AddActionListener(new MyActionListener1());
myView.myBtn2AddActionListener(new MyActionListener2());
}
}
那么,鉴于上述两种情况,哪种方法更好呢?
谢谢。