Visitar URL original
java-design-pattern/wiki/Singleton.md at master · mquan86/java-design-pattern · GitHub
Skip to content

Latest commit

 

History

History
19 lines (12 loc) · 957 Bytes

Singleton.md

File metadata and controls

19 lines (12 loc) · 957 Bytes

Singleton

Pattern

Ensure that a class only have one instance at anytime.

Recognized by a method always returns the same object instance every time.

There a three common and effective implementation for this pattern in Java:

  1. Eager: Use static initialization to ensure one instance. It is eager initialization, so it could be bad if the object too heavy.
  2. Lazy: Similar to Eager, but there is a holder to hold instance to avoid eager initialization. Instance only is created whenever the get instance method is called.
  3. Enum: This is a trick way use Enum type to ensure one instance and simple implementation. This style is introduced in "Effective Java" book

Example

An application must have only one Configuration instance at anytime.