Java Reference
In-Depth Information
the saying goes, you can have too much of a good thing! How can you know when you
should use a service or when it would be better to use another approach, such as a
static factory method or simple dependency injection?
4.1.3
When to use services
The best way to decide when to use a service is to consider the benefits: less coupling,
programming to interfaces, additional metadata, and multiple implementations. If
you have a situation where any of these make sense or your current design provides
similar benefits, you should use a service.
The most obvious place to use a service is between major components, especially if
you want to replace or upgrade those components over time without having to rewrite
other parts of the application. Similarly, anywhere you look up and choose between
implementations is another candidate for a service, because it means you can replace
your custom logic with a standard, recognized approach.
Services can also be used as a substitute for the classic listener pattern . 3 With this pat-
tern, one object offers to send events to other objects, known as listeners . The event
source provides methods to subscribe and unsubscribe listeners and is responsible for
maintaining the list of listeners. Each listener implements a known interface to
receive events and is responsible for subscribing to and unsubscribing from the event
source (see figure 4.6).
Implementing the listener pattern involves writing a lot of code to manage and
register listeners, but how can services help? You can see a service as a more general
form of listener, because it can receive all kinds of requests, not just events. Why not
save time and get the service framework to manage listeners for you by registering
them as services?
To find the current list of listeners, the sender queries the service framework for
matching services (see figure 4.7). You can use service metadata to further define and
filter the interesting events for a listener. In OSG i, this is known as the whiteboard
pattern ; you'll use this pattern when you update the paint example to use services in
section 4.4.
Send events
Event source
Listeners
Sources
Listener
Subscribe/Unsubscribe
Figure 4.6 Listener pattern
3
Brian Goetz, “Java theory and practice: Be a good (event) listener,” www.ibm.com/developerworks/java/
library/j-jtp07265/index.html .
Search WWH ::




Custom Search