All Java singleton patterns (both this and the standard with private constructor and static accessor) have this bad property that if you to test them (or test anything that even remotely depends on them) can use this and only this object.
For example if you want to test PrintingService
class that depends on PrintingSingleton
you will not be able to replace this printing singleton with a mock because it is bound statically.
i.e. imagine testing this function
boolean printDocument(Document d) {
if (PrintingSingleton.INSTANCE.isPrinterEnabled()) {
PrintingSingleton.INSTANCE.print(d);
}
throw new RuntimeExeption("Printing not enabled");
}
with a test
@Test(expectedExceptions = {RuntimeException.class})
public void testPrinting() {
PrintingService service = ...
service.print(new Document()); // How will you simulate
// throwing an exception?
}
Personally, I would just avoid using singletons that way but rather introduce dependency injection, via Guice, Spring or Pico Container. That way you ensure existence of only one object, while not limiting yourself to not being able to mock the object out for example for tests.