Java Reference
In-Depth Information
private void init () {
/* Do initialization */
// This method should be the only way to get a reference
// to the instance
public static synchronized Singleton getInstance () {
if ( initialized ) return instance ;
instance . init ();
initialized = true ;
return instance ;
The crucial point is that for the singleton pattern to be effective, it must be impossi‐
ble to create more than one of them, and it must be impossible to get a reference to
the object in an uninitialized state (see later in this chapter for more on this impor‐
tant point). To achieve this, we require a private constructor, which is only called
once. In our version of Singleton , we only call the constructor when we initialize
the private static variable instance . We also separate out the creation of the only
Singleton object from its initialization—which occurs in the private method
init() .
With this mechanism in place, the only way to get a reference to the lone instance of
Singleton is via the static helper method, getInstance() . This method checks the
flag initialized to see if the object is already in an active state. If it is, then a refer‐
ence to the singleton object is returned. If not, then getInstance() calls init() to
activate the object, and flicks the flag to true , so that next time a reference to the
Singleton is requested, further initialization will not occur.
Finally, we also note that getInstance() is a synchronized method. See Chapter 6
for full details of what this means, and why it is necessary, but for now, know that it
is present to guard against unintended consequences if Singleton is used in a
multithreaded program.
Singleton, being one of the simplest patterns, is often over‐
used. When used correctly, it can be a useful technique, but
too many singleton classes in a program is a classic sign of
badly engineered code.
The singleton pattern has some drawbacks—in particular, it can be hard to test and
to separate out from other classes. It also requires care when used in mulithreaded
code. Nevertheless, it is important that developers are familiar with, and do not
accidentally reinvent it. The singleton pattern is often used in configuration man‐
agement, but modern code will typically use a framework (often a dependency
Search WWH ::

Custom Search