本小节将使用上述的框架重新实现前面的例子,提供对于并发的支持。第一步先完成对于MethodRequest的实现,对于我们的例子来说实现如下: class SayHello implements MethodRequest { public SayHello(Service s) { _service = s; }
publicvoid call() { _service.sayHello(); }
private Service _service; }
该类完成了对于服务提供接口sayHello方法的封装。接下来定义一个服务代理类,来完成请求的封装、排队功能,当然为了做到对Client透明,该类必须实现Service接口。定义如下: class ServiceProxy implements Service { public ServiceProxy() { _service = new ServiceImp(); _active_object = new ActiveObject(); }
publicvoid sayHello() { MethodRequest mr = new SayHello(_service); _active_object.enqueue(mr); }
private Service _service; private ActiveObject _active_object; }
其他的类和接口定义不变,下面对比一下并发逻辑增加前后的服务调用的变化,并发逻辑增加前,对于sayHello服务的调用方法: Service s = new ServiceImp(); Client c = new Client(s); c.requestService();
并发逻辑增加后,对于sayHello服务的调用方法: Service s = new ServiceProxy(); Client c = new Client(s); c.requestService();