通过构造函数传递参数 [英] Passing a parameter through constructor
问题描述
首先,我将简要介绍一些紧密耦合的类(尽管不是最坏的情况):
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);
...
}
}
我相信第二种设计可以视为松耦合,因为它不是使用 setter
而是通过构造函数传递引用,同时定义了自己的 HasText
接口(因为Swing似乎没有,而且我没有找到 JtextComponent
和 JLabel
具有 setText()
方法)。你同意吗?
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?
推荐答案
您的第二个示例将文本视图组件传递给实现 ActionListener
的类。相反,请考虑扩展 AbstractAction
允许集中处理动作事件。对于特定的文本组件, TextAction
提供对焦点文本组件和 Document
模型的访问> JTextComponent 进行监听。作为具体示例,请在此处和此处,此类预定义操作在整个 EditorKit
层次结构中使用。
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.
用于定期操作,例如响应计时器可能发生的情况,请考虑让 ActionListener
更新文本组件的 Document
;侦听视图将自动更新以响应。在这种情况下,侦听器的构造函数将收到对文本组件模型的引用。
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.
这篇关于通过构造函数传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!