如何在不使用返回值的情况下从 B 类中的方法更新 A 类中的对象?
例如:
public class A {
//my main class
private javax.swing.JTextField txtField1;
//a text field (txtField1) is initialized in this class and drawn
}
public class B {
public void doSomething(){
//does something and updates the txtField1 in class A
}
}
Run Code Online (Sandbox Code Playgroud)
再一次,我不想使用return,因为我的 return 已经从同一个方法返回另一个值。
有很多方法可以实现这一目标。最简单的方法是将对象传递给类 B 中的方法:
public void doSomething(JTextField fieldToUpdate){
//your logic here
fieldToUpdate.setText("something");
}
Run Code Online (Sandbox Code Playgroud)
然后就可以直接更新了fieldToUpdate。这不是一个很好的设计模式,因为它直接将一个类拥有的变量的控制暴露给另一个类。
另一种选择是将 A 类的实例传递给方法并在其上调用公共方法:
public void doSomething(A aInstance){
//your logic here
aInstance.setText("something");
}
Run Code Online (Sandbox Code Playgroud)
然后在 A 类中,您需要定义
public void setText(String text){
txtField1.setText(text);
}
Run Code Online (Sandbox Code Playgroud)
这要好一些,因为 B 类不能直接访问 A 类的内部。
一个更封装的响应(尽管对于如此简单的情况可能有点过分)是定义一个接口并将实现该接口的类的实例传递给类 B 中的方法:
public void doSomething(TextDisplayer txt){
//your logic here
txt.setText("something");
}
Run Code Online (Sandbox Code Playgroud)
然后在a类:
public class A implements TextDisplayer{
public void setText(String txt){
txtField1.setText(txt);
}
}
Run Code Online (Sandbox Code Playgroud)
然后是界面:
public interface TextDisplayer{
public void setText(String txt);
}
Run Code Online (Sandbox Code Playgroud)
这种方法的优点是它使 B 类与 A 类完全分离。它所关心的只是传递了一些知道如何处理 setText 方法的东西。同样,在这种情况下,它可能是矫枉过正,但正是这种方法使您的类尽可能解耦。
| 归档时间: |
|
| 查看次数: |
10405 次 |
| 最近记录: |