是的,Java 绝对是对象的引用传递。
但是你所做的是你Writer
假设你GUI
是一成不变的,这意味着它总是有一个名为textBox
.
仅从外观上看,Writer
不应该负责访问和操作GUI
. 如果您更改 . 中的内容GUI
,您还需要重新编码Writer
课程。
您可以将您的代码重新编码Writer
为仅向其发送一条消息,GUI
因为它的职责只是告诉GUI
您要写什么,而不是如何写。然后将其留给GUI
处理该消息:
class GUI
{
Writer w;
void initGUI()
{
w = new Writer(this);
}
void ReceiveMessage(string message)
{
this.textBox.text = message;
}
}
你的Writer
班级:
class Writer
{
GUI ui;
public Write(GUI ui)
{
this.ui = ui;
// Don't send the message in the constructor.
}
// The program calls this function with whatever text the user enters.
public void SendMessage(string message)
{
ui.ReceiveMessage(message);
// Writer no longer depends on ui to have a textbox Element.
}
}
上面的代码可以通过接口进行改进。这样,您可以将任何需要知道如何接收消息的内容传递给您的作者:
interface IMessageReceiver
{
void ReceiveMessage(string message);
}
现在,你GUI
变成了一个 IMessageReceiver:
class GUI implements IMessageReceiver
{
Writer w;
void initGUI()
{
w = new Writer(this);
}
public void ReceiveMessage(string message)
{
this.textBox.text = message;
}
}
Writer
现在上课:
class Writer
{
IMessageReceiver receiver;
public Write(MessageReceiver receiver)
{
this.receiver = receiver;
// Don't send the message in the constructor.
}
// The program calls this function with whatever text the user enters.
public void SendMessage(string message)
{
receiver.ReceiveMessage(message);
}
}
这里的区别是Writer
不再关心它是否是GUI
. 只要它IMessageReceiver
知道如何接收消息,它就会接受任何对象。
如果您不熟悉接口,请对其进行一些阅读/研究。它们非常方便,如果不是,至关重要!