Injectable Singleton

From APIDesign

(Difference between revisions)
Jump to: navigation, search
(Injectable Meta-Singleton)
Line 75: Line 75:
== Injectable Meta-Singleton ==
== Injectable Meta-Singleton ==
-
TBD:
+
As mentioned earlier, there are two recommended ways to configure the [[Injectable Singleton]]s. You can rely on [[Java]]'s standard [[ServiceLoader]] or you can choose [[Lookup]] library. Of course, it is often preferable to have as little dependencies as possible (and thus the [[ServiceLoader]] shall be natural choice), however the [[Lookup]] library offers certain advantages that make it attractive. Most of them are listed [[Lookup|elsewhere]], but let me point your attention to one, relevant for topic of this page.
-
* Lookup is meta!
+
 
-
* Show [[dependency injection]] cooperation? Anybody wants to see that?
+
[[Lookup]] is a [[singleton]]. In fact it is an [[Injectable singleton]]! There is a ''Lookup.getDefault()'' method which returns a ''meta''-factory for all [[Injectable Singleton]]s, and this factory is also [[injection|injectable]]. As a result (in contrary to [[ServiceLoader]]) one can completely customize the way all [[Injectable singleton]]s in a system are discovered and created.
 +
 
 +
One can even use [[SpringAndLookup]] bridge, register [[Lookup]] that wraps a [[Spring]]'s [[XML]] configuration file and then one can configure whole application using classical [[Dependency Injection]] tricks (I can provide an executable demo, if there is an interest; just [[talk:Injectable Singleton|leave a note]]).
== Polemic ==
== Polemic ==

Revision as of 21:14, 8 February 2010

Singletons are sometimes dishonest as a design anti-pattern. Right, one may use them improperly, but with guidance of proper methodology there is nothing wrong on singletons. This page provides step by step cook book for usage of so called Injected Singletons.

Contents

What this is not

We are going to introduce an enhanced version of the singleton pattern that supports testability, provides smooth Convention over Configuration and Component Injection. It can be seen as nice alternative companion to application context used by dependency injection.

However when talking about singleton pattern, don't imagine Java's SecurityManager or URLStreamHandlerFactory. Those are not Injectable Singletons, they require non-trivial amount of initialization code and basically let your application knowledge leak out through out the system.

Defining the Singleton

Imagine you want to create a singleton service to display questions to the user. This would be your API:

does not exists: singletons.injectable.api

Slightly surprising thing is that the class is abstract (e.g. it contains no implementation) and to allow extensibility it provides protected constructor. This is not what traditional singletons usually do, but remember this is an Injectable Singleton!

As the important motto of Injectable Singletons is Convention over Configuration each such singleton needs to define default (even dummy) implementation. Let's do it like this:

does not exists: singletons.injectable.dummyimpl

In this case, the implementation of the yesOrNo method is really trivial and not very useful, but often there are cases when the default behavior can be made acceptable for many purposes.

Now the time as come to write proper initialization code (that will support extensibility). We can do it either in Java6 standard way via ServiceLoader:

does not exists: singletons.injectable.serviceloader

Or using small Lookup library (we'll see later what benefit it provides):

does not exists: singletons.injectable.lookup

And that is all. Our first, Injectable Singleton is ready for being used.

Usage

To use a singleton, it is enough to import its API class and call its methods. Because singletons are inherently initialized - e.g. as soon as one calls their static getter, one gets initialized instance - there is no need for any special configuration in the client code. Just:

does not exists: singletons.injectable.usage

This makes the whole use as simple as possible by following half of the Convention over Configuration motto: If you are OK with default implementation, just use it. As soon as you link with the API class, you can be sure that you'll get reasonable implementation. No other configuration is needed. This is the output of such sample execution:

$ java -jar DisplayerMain.jar -cp Displayer.jar
Saying no to 'Do you like singletons?'
Visit http://singletons.apidesign.org to change your mind!

Configure

Of course, using the dummy implementation is not always optimal. As our systems get more and more assembled at deploy time there especially needs to be a way to support easy configuration during application deployment. This is inherently supported due to adherence to Java Standard Extension Mechanism. Any time later, in any additional project that produces completely independent JAR file one can compile following piece of code:

does not exists: singletons.injectable.implement

The JAR containing this class (and the generated META-INF/services/ entry, as generated by processing @ServiceProvider annotation via compile time AnnotationProcessor or alternatively created manually) can be put onto the application classpath. As soon as you do

$ java -jar DisplayerMain.jar -cp Displayer.jar:DefaultDisplayerImpl.jar

your system will get properly configured and will use the injected enhanced singleton:

Image:Singleton.png

Don't waste time writing configuration files! All you need to do to configure Injectable Singletons is to include correct JARs on application classpath. Follow the second part of the Convention over Configuration motto. Let application assemblers dissatisfied with default, drop-in their implementations to classpath!

Testability

Of course, these days one just has to write code that is inherently testable. One of the critiques of singleton pattern was that it does not allow this. That it is not possible to mock in different singleton behavior during test execution. Injectable Singletons are here to allow you to do exactly this:

does not exists: singletons.injectable.test

The first thing the test does, is to inject its own, mock implementation of singleton via utility class MockServices. Then the whole test execution is using this instance, which is obviously enhanced to allow easy testability.

I shall however mention an important restriction. Because Injected Singletons support class-level co-existence, each set of tests that get linked together share the same singletons. This may not be always appropriate - in such case split your test into two classes and make sure they get executed in a separate VM.

Injectable Meta-Singleton

As mentioned earlier, there are two recommended ways to configure the Injectable Singletons. You can rely on Java's standard ServiceLoader or you can choose Lookup library. Of course, it is often preferable to have as little dependencies as possible (and thus the ServiceLoader shall be natural choice), however the Lookup library offers certain advantages that make it attractive. Most of them are listed elsewhere, but let me point your attention to one, relevant for topic of this page.

Lookup is a singleton. In fact it is an Injectable singleton! There is a Lookup.getDefault() method which returns a meta-factory for all Injectable Singletons, and this factory is also injectable. As a result (in contrary to ServiceLoader) one can completely customize the way all Injectable singletons in a system are discovered and created.

One can even use SpringAndLookup bridge, register Lookup that wraps a Spring's XML configuration file and then one can configure whole application using classical Dependency Injection tricks (I can provide an executable demo, if there is an interest; just leave a note).

Polemic

One of the critics mentioned that this is not really a singleton, as it allows multiple instances to be created. Yes, people can subclass the abstract class and create as many instances as they want. However whoever uses just the static API getter, is guaranteed to receive only one, shared instance. For those who use the ClientAPI part of such singleton, the whole things appears to be singleton. That is why this worry is more about beauty than real world problems.

TBD:

Personal tools
buy