Singleton: Difference between revisions

1,588 bytes added ,  28 days ago
Add Ecstasy example
(Dialects of BASIC moved to the BASIC section.)
(Add Ecstasy example)
 
(3 intermediate revisions by 3 users not shown)
Line 839:
# ...
}</syntaxhighlight>
 
=={{header|Ecstasy}}==
The <code>static</code> keyword in a class declaration will compile that class as a singleton. It is legal to define <code>const</code> (i.e. immutable) and <code>service</code> classes as singletons. Modules, packages, and enumeration values are always singleton classes. It is <b>not</b> legal to define normal <code>class</code> classes as singletons, because normal classes are mutable, and Ecstasy does not allow shared mutable state.
 
The name of the class is used to specify that singleton instance:
 
<syntaxhighlight lang="ecstasy">
module test {
static service Singleton {
private Int counter;
String fooHasBeenCalled() {
return $"{++counter} times";
}
}
 
void run() {
@Inject Console console;
for (Int i : 1..5) {
console.print($"{Singleton.fooHasBeenCalled()=}");
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
x$ xec test
Singleton.fooHasBeenCalled()=1 times
Singleton.fooHasBeenCalled()=2 times
Singleton.fooHasBeenCalled()=3 times
Singleton.fooHasBeenCalled()=4 times
Singleton.fooHasBeenCalled()=5 times
</pre>
 
=={{header|Eiffel}}==
Line 1,010 ⟶ 1,043:
Works with any ANS Forth
 
Needs the FMS-SIFMS2VT (singleForth inheritance) library codeextension located here:
https://github.com/DouglasBHoffman/FMS2/tree/master/FMS2VT
http://soton.mpeforth.com/flag/fms/index.html
<syntaxhighlight lang="forth">include FMS-SIFMS2VT.f
\ A singleton is created by using normal Forth data
Line 1,303 ⟶ 1,336:
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>
Line 2,319 ⟶ 2,370:
 
In practice, it's unlikely anyone would bother; they'd just create a class with static methods and/or fields only which is effectively a singleton as there's only ever a single instance of a static field.
<syntaxhighlight lang="ecmascriptwren">class Singleton {
// Returns the singleton. If it hasn't been created, creates it first.
static instance { __instance == null ? __instance = Singleton.new_() : __instance }
162

edits