1

我在 java 中有一个 A 类,它在变量 alpha 中设置一个值。类 A 调用接口“MessageListener”的函数,如下所示:

private List<MessageListener> mListeners;

for (MessageListener ml : this.mListeners) 
{
ml.messageTransferred(aMessage, from, this.host, isFirstDelivery);
}

我想将 alpha 传递给实现上述接口的 MessageStatsReport.java 类的 messageTransferred 函数。

如果我修改 messageTransferred 函数的参数,这会影响来自同一接口 (MessageListener) 的 12 个其他类。那么什么是简单的出路呢?如何调用在 A 类中设置的(非静态)变量值。请帮忙?

4

2 回答 2

1

接下来制作方法

messageTransferred(aMessage, from, this.host, isFirstDelivery, alpha)  
{   
   if (alpha != null)  
   {
   // ...  
}  

现在,当您想将 alpha 传递给方法时,请使用

messageTransferred(aMessage, from, this.host, isFirstDelivery, alpha);  

当你不想使用 alpha 时,传递null而不是 alpha

messageTransferred(aMessage, from, this.host, isFirstDelivery, null); 
于 2012-09-03T19:24:52.683 回答
1

If the array of messageListeners is called by A then how is any MessageListener supposed to 'know' about alpha? A called method can not access properties or methods of the callee inside of it since the type of the callee may change. You have to pass alpha around if you want A to be aware of it.

Notice that you are changing the contract that MessageListener defines by having it deal with another parameter, if it were possible to breach the interface's contract without anyone knowing about it, well that wouldn't make any sense (in java's perspective, some languages do allow this).

You are passing a message, shouldn't alpha be a part of that message? in what format is aMessage?

One solution is to define an interface that defines that what an actual message transfered looks like. In a simplified way, you can have a message interface and have a SimpleMessage and ComplicatedMessage that implement it. aMessage can be of that type and you can handle the contents based on what the interface defined.

于 2012-09-03T19:16:21.433 回答