1
我在Java中使用MVP的設計模式編寫GUI應用程序。 JButton
對象屬於View類,ActionListener
對象屬於Presenter。我在尋找一個簡潔的方式,讓演示者ActionListener
s添加到視圖的JButtons
無:(1)使按鈕public
和(2),而不必一堆的方法添加到看起來像揭露查看的Jbutton將簡潔的方式反對主持人
private JButton foo;
private JButton bar;
public void addActionListenerToButtonFoo(ActionListener l) {
foo.addActionListener(l);
}
public void addActionListenerToButtonBar(ActionListener l) {
bar.addActionListener(l);
}
// (imagine typing 10 more of these trivial functions and having
// them clutter up your code)
我發現一個技術,效果相當好:
public class View {
class WrappedJButton {
private JButton b;
public WrappedJButton(String name){
this.b = new JButton(name);
}
public void addActionListener(ActionListener l) {
b.addActionListener(l);
}
}
public final WrappedJButton next = new WrappedJButton("Next");
public final WrappedJButton prev = new WrappedJButton("Previous");
public void setup() {
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout());
buttons.add(previous.b);
buttons.add(next.b);
}
} // end view
class Presenter {
public Presenter() {
View view = new View();
view.next.addActionListener(event -> {
// Respond to button push
});
}
} // end Presenter
此包裝效果很好。製作包裝的按鈕public
允許演示者通過名稱引用它們(這允許我的IDE使用代碼完成);但是,因爲它們是WrappedJButton
對象,所以Presenter只能添加一個ActionListener。通過在私人b
字段中抓取「真實」按鈕,視圖可以「完全」訪問對象。
問題:
- 是否有一個更好/更清潔的解決方案?或許有些 將消除需要訪問View中的
b
場? - 有沒有辦法來概括這個解決方案,所以我不必 剪切和粘貼
WrappedJButton
到每一個視圖類我寫?我 試圖移動WrappedJButton
到接口(其查看 器具);但是,當我這樣做,查看不再具有訪問 私人b
場。