Java Reference
In-Depth Information
The service locator has some interesting benefits. First, it is not possible to change the service imple-
mentation at runtime. Second, the service provider is a singleton, but the services don't have to be.
You can still prevent multiple instantiation, but instead of making five singletons globally accessible,
everything can now go through one single locator. Third, adding services is just a simple manner of
adding a field and the getter and setter methods.
In essence, the service provider pattern is a combination of a singleton and strategy pattern (as you'll
see later).
One thing that you do need to consider, however, is remembering to set all services. When you for-
get to call the setLogger method in this example, for instance, the ServiceProvider will return
null . There are several ways around this. You can manually check in your code to see if a provider
returns null , you can force initialization by accepting a Logger object in the ServiceProvider
constructor, or you can just initialize the service to a default one. Finally, you can also apply another
pattern, the null object pattern, to solve this issue.
The basic idea of the null object is that instead of returning null, a special object returning the same
interface as the desired object is returned, but with an implementation that does nothing. In the log-
ging example, a NullLogger would look like this:
public class NullLogger implements Logger {
public void logMessage(String message, int PRIORITY_LEVEL) {
// Do nothing
}
}
As you can see, this service implements all expected methods, but does not actually do anything.
Now, when you default to this service in your provider class, the calling code doesn't have to handle
null s.
NOTe The discussion on the null object pattern is also related to another
commonly observed best practice, namely the fact that it is always better—
whenever possible—to have functions return empty collections (collections
containing zero elements) instead of a null value). A common reason why
programmers choose to return null in the first place is to signal to the calling
code that some kind of error occurred (the collection could not be retrieved or
constructed), which is different from a successful execution returning an empty
collection. In this case (signaling errors), the better practice is to rely on excep-
tions, which can be caught and handled accordingly by calling code. Following
this practice will help greatly to avoid null pointer exceptions (e.g., by calling
the size() method on a null object).
(abstract) Factory Pattern
The factory pattern is another commonly applied creational pattern. It's summarized as follows:
Defer instantiation of a class to subclasses .
In other words, the factory pattern provides an interface for creating an object, while providing dif-
ferent implementations for the creation of that object.
 
Search WWH ::




Custom Search