現在、Java で Blackjack アプリケーションをプログラミングしていますが、MVC アーキテクチャで記述する必要があります。モデル、ビュー、コントローラーはすべて完全にコーディングされており、すべてが完全に機能しています。しかし、リスナーをコンポーネントにアタッチする最良の方法は何か (JButton など) を考えています。
My current design declares all components in the view that need listeners as public final. It then passes the view to the controller. From there, the controller has full reign to access the components and add action listeners. Code example:
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());
}
}
However, one of my friends has declared all his JButton's with private scope and then made public methods in the view to add action listeners to their respective components. To me, this just seems like a waste of time and only adds unnecessary code. Code example:
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());
}
}
So, given the two scenarios above, which is the better way?
Thanks.