The singleton pattern is one of the creational patterns described in the GoF 1 book. A singleton
class guarantees the production of only one instance of its own type. Having only one instance
can be useful in several cases, such as with global access and when caching expensive resources;
however, it may introduce some problems of race conditions if the singleton is used in a multithread
environment. Because most programming languages do not provide a built‐in mechanism to create
singletons, developers must code their own implementations.
However, Java EE has a built‐in mechanism that gives the developer a simple way to create a
singleton via the addition of an annotation to the class.
WHAT IS A SINGLETON?
According to GoF, the singleton pattern is used to “ensure a class only has one instance, and provide
a global point of access to it.” Head First Design Patterns 2 offers the same explanation and points.
Singletons are often used in combination with factory patterns (discussed in Chapter 6, “Factory Pattern”).
Singletons are commonly used for the following purposes and situations:
To access shared data across the whole application domain, such as coni guration data
To load and cache expensive resources only once, allowing global shared access and improve
To create an application logger instance, because normally only one is required
To manage objects within a class implementing the factory pattern
To create a façade object, because normally only one is necessary
To lazily create static classes, since singletons can be lazily instantiated
Spring uses singletons when creating beans (by default, Spring beans are singletons), and Java EE
uses singletons internally, such as in the service locator. Java SE also uses the singleton pattern in the
implementation of the runtime class. So singletons are dei nitely helpful if you use them in the right
Nevertheless, the aggressive use of the singleton pattern may mean unnecessarily caching resources
and not letting the garbage collector reclaim objects and free valuable memory resources. It also may
mean you do not really use the advantages of object creation and inheritance. An unusually high
usage of singletons is considered a sign of poor object‐oriented design, which may cause memory and
performance issues. Another problem is that singletons are not great
when it comes to unit testing. Later, this chapter discusses in more
detail the issues surrounding the use of the singleton pattern.
- instance: Singleton
Singleton Class Diagram
As you can see from the class diagram in Figure 4-1, the singleton
pattern is based on a single class that holds a reference to the only
instance of itself while controlling its creation and its access via the
single getter method.
- Singleton ( )
+ getInstance ( ) : Singleton
FIGURE 4-1 The singleton
pattern class diagram