Java Reference
In-Depth Information
OSGi
service
registry
Publish
Discover
Figure 4.14 Painting with services
4.4.3
Tracking shape ser vices
Remember the DefaultShape class that acted as a simple proxy to an underlying
shape bundle in section 3.4? When the referenced shape bundle was active, the
DefaultShape used its classes and resources to paint the shape. When the shape bun-
dle wasn't active, the DefaultShape drew a placeholder image instead. You can use the
same approach with services, except that instead of a bundle identifier, you use a ser-
vice reference as shown here:
if (m_context != null) {
try {
if (m_shape == null) {
m_shape = (SimpleShape) m_context.getService(m_ref);
}
m_shape.draw(g2, p);
return;
} catch (Exception ex) {}
}
This code gets the referenced shape service and draws a shape with a simple method
call. A placeholder image is drawn instead if there's a problem.
You can also add a dispose() method to tell the framework when you're finished
with the service:
public void dispose() {
if (m_shape != null) {
m_context.ungetService(m_ref);
m_context = null;
m_ref = null;
m_shape = null;
}
}
The new DefaultShape is now based on an underlying service reference, but how do
you find such a reference? Remember the advice from section 4.3.3: you want to use
several instances of the same service and react as they appear and disappear, but you
don't want detailed control—you need a ServiceTracker .
Search WWH ::




Custom Search