Member-only story
Effective Java: Singletons
Time for chapter three of our Effective Java review. Today’s is a fairly simple one. Today we are talking about the singleton pattern. The singleton pattern is quite well known and basically comes down to an object that only allows instantiation once.
So what benefits does a singleton give us?
- Expensive objects can be avoided being generated multiple times.
- If there is a reason we shouldn’t have an unbounded amount of objects we can own instance control.
What about some cons:
- They are extremely hard to test (having your singleton implement an interface can help this some)
- They basically serve as global state that can be complex and cause bugs.
So a singleton is definitely not without it’s costs but let’s say we have determined that we do need a singleton, what are our options of implementing the pattern? Well Effective Java goes through three methods all including hiding the constructor of the object in one way or another.
Option 1: public constant field
The first option that is described is quite simple. The first step is to create a private constructor. After that you simply create a public static final field that instantiates the object to be used. Let’s look at an example: