Singleton: Difference between revisions
Content added Content deleted
(→{{header|Java}}: Add Enum as a singleton) |
|||
Line 1,303: | Line 1,303: | ||
public static Singleton getInstance() { |
public static Singleton getInstance() { |
||
return LazyHolder.INSTANCE; |
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> |
}</syntaxhighlight> |