java消息 回调,Java实现来处理回调消息

I have the following situation I need to handle in my code:

public class Class1 {

IRequester requester;

public Class1(Requester impl) {

requester = impl;

}

public List doSomething() {

requester.request1(); // sends messages to a set of nodes

//do some more local processing

list = requester.request2(); // sends some more messages and returns a list

return list;

}

}

In this case request1() sends a request to a set of nodes and returns a result which will be used locally for more processing, and then the request2() is made which returns a list. This needs to be returned at the end of execution of doSomething(). request1() and request2() are done through requester which is of type IRequester

public interface IRequester {

request1();

List request2();

}

Now request1() and request2() are implemented by the class which actually does the requests. This is the class that handles the communication between the nodes.

public NetworkManager implements IRequester {

request1() {

// Create an operation

// Add callback to the operation

// schedule operation

}

request2() {

}

}

Now, my issue is that when I implement request1() here in there I need to create a procedure which will send a message to the node. This procedure can have a callback attached. When the node responds it returns the result. How do I implement this such that it returns the result at the end of my request1?

解决方案

Since the return type of request1() is void so you cannot return value from it .

But in the implementation class of IRequester , you can pass a resultObject ,

whenever the request1() method is execute it will store the result in the result Object, and when you need to get the result , you can get it from the ResultObject

class ResultObject{

getResult(); ///return result

setResult(); ///store result

}

public NetworkManager implements IRequester {

private ResultObject callBackResult;

public ResultObject getResult(){

return callBackResult;

}

public void setResult(ResultObject value){

this.callBackResult=value;

}

request1() {

// Create an operation

this.setResult(callProcedure());

// schedule operation

}

request2() {

}

}

public class Main{

public static void main(String args){

IRequester r=new NetworkManger();

ResultObject res=new ResultObject();

r.setResult(res);

r.request1();

r.getResult();

r.request2();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值