title: OSGi services - best practice
body: <p>I start loving OSGi services more and more and want to realize a lot more of my components as services. Now I'm looking for best-practice, especially for UI components. </p>
  
  <p>For Listener-relations I use the whiteboard-pattern, which IMHO opinion is the best approach. However if I want more than just notifications, I can think of three possible solutions.</p>
  
  <p>Imagine the following scenario:</p>
  
  <pre><code>interface IDatabaseService {
    EntityManager getEntityManager();
  }
  </code></pre>
  
  <p><strong>[1] Whiteboard Pattern - with self setting service</strong></p>
  
  <p>I would create a new service interface:</p>
  
  <pre><code>interface IDatabaseServiceConsumer {
    setDatabaseService(IDatabaseService service);
  }
  </code></pre>
  
  <p>and create a declarative IDatabaseService component with a <em>bindConsumer</em> method like this</p>
  
  <pre><code>protected void bindConsumer(IDatabaseServiceConsumer consumer) {
   consumer.setDatabaseService(this);
  }
  protected void unbindConsumer(IDatabaseServiceConsumer consumer) {
   consumer.setDatabaseService(null);
  }
  </code></pre>
  
  <p>This approach assumes that there's only one IDatabaseService.</p>
  
  <p><strong>[Update]</strong> Usage would look like this:</p>
  
  <pre><code>class MyUIClass ... {
  
  private IDatabaseService dbService;
  
  Consumer c = new IDatabaseServiceConsumer() {
   setDatabaseService(IDatabaseService service) {
    dbService = service;
   }
  }
  Activator.registerService(IDatabaseServiceConsumer.class,c,null);
  ...
  }
  </code></pre>
  
  <p><strong>[2] Make my class a service</strong></p>
  
  <p>Image a class like</p>
  
  <p>public class DatabaseEntryViewer extends TableViewer</p>
  
  <p>Now, I just add bind/unbind methods for my IDatabaseService and add a component.xml and add my DatabaseEntryViewer. This approach assumes, that there is a non-argument constructor and I create the UI components via a OSGi-Service-Factory.</p>
  
  <p><strong>[3] Classic way: ServiceTracker</strong></p>
  
  <p>The classic way to register a static ServiceTracker in my Activator and access it. The class which uses the tracker must handle the dynamic.</p>
  
  <p>Currently I'm favoring the first one, as this approach doesn't complicated object creation and saves the Activator from endless, static ServiceTrackers.</p>