[Effective Java] [Item 3] Enforce the singleton property with a private constructor or an enum type

Опубликовано: 09 Апрель 2026
на канале: Omkar Shetkar
1,620
21

Creating and Destroying Objects

Item 3: Enforce the singleton property with a private constructor or an enum type

A singleton is simply a class that is instantiated exactly once.
Making a class a singleton can make it difficult to test its clients

Before release 1.5, there were two ways to implement singletons:
1. public member is a final field
the lack of public or protected constructor guarantees unique object
Advantages:
public static final field makes it clear that it is singleton
2. public member is a static factory method
public static factory method can be changed without affecting clients

Enum singleton - the preferred approach
it is more concise
provides the serialization machinery for free
provides ironclad guarantee against multiple instantiation

A Single-element enum type is the best way to implement a singleton.