Java Reference
In-Depth Information
When you do need a single instance of a class, think about whether the instance also has to
be globally accessible.
If you do need a single instance of a class and it has to be globally accessible, you can use the
full singleton pattern. Always be wary of this option, and make sure you've exhausted the
other options mentioned here first.
As discussed, most singletons offer some general “helper” methods or provide a global centralized
service for use in the rest of the application, such as a logging functionality. To avoid having a global
collection of singleton objects, it is a good idea to group your singletons under a service provider, as
described in the next pattern.
Service Provider Pattern and Null Object Pattern
Let's say you have a service offering logging functionality that needs to be called throughout
all parts of your code. Perhaps you should implement it as a static utility class, as you've seen
previously:
LoggingUtils.logMessage("Something bad happened", LoggingUtils.PRIORITY_HIGH);
Or perhaps create a singleton:
Logger.getInstance().logMessage("Something bad happened", Logger.PRIORITY_HIGH);
Disregarding the fact that this approach introduces some nasty global objects in the project, you still
have the problem that these objects are very tightly coupled with the rest of the code. What if at one
point you want to introduce a second logging system and decide which one to use at runtime?
The service provider pattern can help, because it allows you to keep a “registry” of services and
swap them in and out at runtime. This is illustrated in the logging example. Imagine you have a
Logger interface and two concrete implementing classes, ConsoleLogger and EmailLogger (an
AbstractLogger can be defined here as well, for instance to hold the different priority level con-
stants). Your service locator would then look like this:
public class ServiceProvider {
private static final ServiceLocator INSTANCE = new ServiceLocator();
private ServiceLocator() {}
private Logger logger;
public static ServiceLocator getInstance() {
return INSTANCE;
}
private Logger getLogger() {
return logger;
}
private void setLogger(Logger logger) {
this.logger = logger;
}
}
 
Search WWH ::




Custom Search