Jump to content

Singleton: Difference between revisions

→‎{{header|Java}}: Add Enum as a singleton
(→‎{{header|Java}}: Add Enum as a singleton)
Line 1,303:
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}</syntaxhighlight>
 
===Thread-Safe Using Enum ===
Enums in Java are fully-fledged classes with specific instances, and are an idiomatic way to create singletons.
<syntaxhighlight lang="java">public enum Singleton {
INSTANCE;
 
// Fields, constructors and methods...
private int value;
Singleton() {
value = 0;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}</syntaxhighlight>
47

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.