问题
First I will present a quick outline of a somewhat tightly coupled classes (though not the worst possible case):
class setUpGUI {
...
JTextField output = new JTextField();
...
CountTimer ct;
...
public void setOtputText(String text) {
output.setText(text);
public startTimer() {
ct = new CountTimer();
}
...
}
class CountTimer implements ActionListener {
private String text = "";
private gui = new SetUpGUI();
...
@Override
public void actionPerformed(ActionEvent e) {
...
gui.setOtputText(text);
...
}
My question is about the second snippet (in comparison with the first and on its own):
// functionally equivalent to com.google.gwt.user.client.ui.HasText
interface HasText {
String getText();
void setText(String text);
}
class setUpGUI {
...
JTextField output = new JTextField();
...
CountTimer ct;
...
public void setOtputText(String text) {
output.setText(text);
public startTimer() {
ct = new CountTimer(output);
}
...
}
class CountTimer implements ActionListener {
private String text = "";
private HasText txtComp;
...
CountTimer(txtComp) {
...
this.txtComp = txtComp;
...
}
@Override
public void actionPerformed(ActionEvent e) {
...
txtComp.setText(text);
...
}
}
I believe that the second design can be considered a loose coupling, since instead of using a setter
it passes a reference through constructor and at the same time defines its own HasText
interface (since Swing does not seem to have one and I didn't find a common parent of JtextComponent
and JLabel
that has setText()
method). Would you agree?
What is the general attitude towards passing a parameter via constructor?
回答1:
Your second example passes a textual view component to a class that implements ActionListener
. Instead, consider a class that extends AbstractAction to allow centralized handling of action events. In the particular case of a text component, TextAction provides access to the focused text component and the underlying Document
model to which the JTextComponent
listens. As concrete examples, outlined here and here, such pre-defined actions are used throughout the EditorKit
hierarchy.
For periodic actions, such as might occur in response to a timer, consider letting the ActionListener
update the text component's Document
; the listening view will update itself automatically in response. In this case, the listener's constructor would receive a reference to the text component's model.
来源:https://stackoverflow.com/questions/22102477/passing-a-parameter-through-constructor