我有一个非常简单的银行账户,我是为了练习我的MVC知识而建立的。但是我遇到了麻烦。
由于存款和提款屏幕基本相同,我几乎将其全部抽象为BaseWindow类。
这是 BaseWindow 类:
public class BaseWindow extends JFrame {
private static final long serialVersionUID = 4741220023341218042L;
JButton executeButton;
public BaseWindow(String title){
super(title);
JPanel panel = new JPanel(new GridLayout(0, 3));
JLabel amountLabel = new JLabel("Amount: ");
JTextField inputBox = new JTextField(15);
executeButton = new JButton("Execute");
JLabel newBalanceLabel = new JLabel("New Balance: ");
JLabel newBalance = new JLabel();
panel.add(amountLabel);
panel.add(inputBox);
panel.add(executeButton);
panel.add(newBalanceLabel);
panel.add(newBalance);
panel.add(new JLabel()); //Empty, for layout purposes
add(panel);
pack();
}
public JButton getExecuteButton(){
return executeButton;
}
}
问题
由于我使用的是Model-View-Controller模式,Execute按钮的功能在Controller类中确定,该类由以下内容组成:
...
public void startDepositWindow(){
DepositWindow depositWindow = view.createDepositWindow();
depositWindow.getExecuteButton().addActionListener(createExecuteButtonListener());
depositWindow.run();
}
public void startWithdrawWindow(){
WithdrawWindow withdrawWindow = view.createWithdrawWindow();
withdrawWindow.getExecuteButton().addActionListener(createExecuteButtonListener());
withdrawWindow.run();
}
//Button Action Listeners
private ActionListener createDepositButtonListener(){
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
startDepositWindow();
}
};
}
private ActionListener createWithdrawButtonListener(){
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
startWithdrawWindow();
}
};
}
private ActionListener createExecuteButtonListener(){
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
// WHAT GOES HERE??
}
};
}
...
问题是,我无法想到createExecuteButtonListener
中的内容,因为我不能简单地说model.deposit()
或model.withdraw()
,因为我不知道执行哪个窗口里面点击了按钮。
据我所知,我不能在这里使用多态,因为监听器没有绑定在DepositWindow
或WithdrawWindow
子类中,我不想在那里调用它们,因为那样会违反了模型 - 视图 - 控制器。
所以困扰我的是,如何告诉按钮监听器/控制器什么是正确的事情?