3. HelloWorldUser
Source code:
HelloWorldUser.java
Like, HelloWorldSimpleUser, HelloWorldUser is a client
that connects to the HelloWorldProvider
service. It does this by registering itself as a listener for
HelloWorldServiceSynchronous providers:
component.useService(HelloWorldServiceSynchronous.class, this);
When you examine HelloWorldUser.java and observe the constructor,
you will see similarities to the constructor in HelloWorldSimpleUser. After
a component is obtained by ComponentFactory.getComponent()
method, component.useService() registers the client
(HelloWorldUser) to be notified about services that implement
the interface provided (HelloWorldProvider, in our case). When
any matches are found, the serviceProvided() method
of the UseServiceListener interface is called. Notice HelloWorldUser
implements the UseServiceListener interface. It looks different than
HelloWorldSimpleUser in that it keeps a list of several providers and it
will receive messages from all of them.
public void serviceProvided (java.lang.Class
serviceInterface, ServiceResult serviceResult)
{
providers.put(serviceResult.getServiceID(), serviceResult.getService());
output(">> Found Provider: " + serviceResult.getServiceID().toString());
}
UseServiceListener is used when a component is to be set as
a listener for some event. In this case, the events being listened
for are "Hello World!" messages sent from HelloWorldProvider.
The serviceProvided() method (see UseServiceListener
interface) receives a ServiceResult object containing a private
variable that is an implementation of the interface subscribed
forin our case, HelloWorldServiceSynchronous.
HelloWorldUser also takes care of the details in displaying the
"Hello World!" messages.
Summary
Conceptually, what happened in this synchronous example is the provider
determined the connector of the service. The listener discovers
the other half of the connector dynamically.
In review, the steps that were used in
developing HelloWorldServiceSync were:
- Define the service interface
- Create an implementation of the service interface
- get a reference to the component
- distribute the object
- provide the distributed object
- Create a client to use the service
- get a reference to a component
- register as a listener for the service
- implement serviceProvided