3. HelloWorldSimpleUser
Source code:
HelloWorldSimpleUser.java
The HelloWorldUser component will
- Create a client to use the service
- get a reference to a component
- register as a listener for the service
- implement serviceProvided
HelloWorldSimpleUser 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);
Examine HelloWorldSimpleUser.java, particularly the constructor. After
a component is obtained by ComponentFactory.getComponent()
method, component.useService() registers the client
(HelloWorldSimpleUser) to be notified about services that implement
the interface provided (HelloWorldProvider, in our case). When
a match is found, the serviceProvided() method
of the UseServiceListener interface is called. We show some of the code
in the implementation of the serviceProvided method here. Notice HelloWorldSimpleUser
implements the UseServiceListener interface.
// here we get the service object
HelloWorldServiceSynchronous provider =
(HelloWorldServiceSynchronous) serviceResult.getService();
// print the message from the service provider
System.out.println(provider.helloWorld() + "\n");
// disconnect from the service
System.out.println(">> Disconnecting from service");
ComponentFactory.getComponent().shutdown();
System.exit(0);
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.
As shown above, HelloWorldSimpleUser displays the result of the service and
then removes itself as a listener of the service.
The next example is a more sophisticated version of the Hello World.