Skip to content

Instantly share code, notes, and snippets.

@RealDeanZhao
Created March 27, 2017 05:19
Show Gist options
  • Save RealDeanZhao/60bef9d33a7b46feae167cbd6726956e to your computer and use it in GitHub Desktop.
Save RealDeanZhao/60bef9d33a7b46feae167cbd6726956e to your computer and use it in GitHub Desktop.
a singleton using enum
```
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
static void main(){
Elvis.INSTANCE.leaveTheBuilding();
}
```
@RealDeanZhao
Copy link
Author

<< Effective Java >> Item 3.

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment