Singleton: Difference between revisions

5,873 bytes added ,  1 month ago
Add Ecstasy example
m (syntax highlighting fixup automation)
(Add Ecstasy example)
 
(9 intermediate revisions by 7 users not shown)
Line 154:
Return val
}</syntaxhighlight>
 
=={{header|BASIC}}==
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">
REM Sacado del forum de FreeBASIC (https://www.freebasic.net/forum/viewtopic.php?t=20432)
 
Type singleton
Public :
Declare Static Function crearInstancia() As singleton Ptr
Declare Destructor ()
Dim i As Integer
Private :
Declare Constructor()
Declare Constructor(Byref rhs As singleton)
Declare Static Function instancia(Byval crear As Integer) As singleton Ptr
End Type
 
Static Function singleton.crearInstancia() As singleton Ptr
Return singleton.instancia(1)
End Function
 
Static Function singleton.instancia(Byval crear As Integer) As singleton Ptr
Static ref As singleton Ptr = 0
Function = 0
If crear = 0 Then
ref = 0
Elseif ref = 0 Then
ref = New singleton
Function = ref
End If
End Function
 
Constructor singleton ()
End Constructor
 
Destructor singleton()
singleton.instancia(0)
End Destructor
 
'-----------------------------------------------------------------------------
Dim As singleton Ptr ps1 = singleton.crearinstancia()
ps1->i = 1234
Print ps1, ps1->i
 
Dim As singleton Ptr ps2 = singleton.crearinstancia()
Print ps2
 
Delete ps1
 
Dim As singleton Ptr ps3 = singleton.crearinstancia()
Print ps3, ps3->i
Delete ps3
Sleep
</syntaxhighlight>
{{out}}
<pre>
2038352 1234
0
2038352 0
</pre>
 
==={{header|OxygenBasic}}===
<syntaxhighlight lang="oxygenbasic">
Class Singleton
static sys inst 'private
int instantiated() { return inst }
void constructor(){ if not inst then inst=@this }
'all other methods start with @this=inst
end class
 
'if not singleton.instantiated
new Singleton MySingleton
'endif
</syntaxhighlight>
 
==={{header|PureBasic}}===
====Native version====
Thread safe version.
<syntaxhighlight lang="purebasic">Global SingletonSemaphore=CreateSemaphore(1)
 
Interface OO_Interface ; Interface for any value of this type
Get.i()
Set(Value.i)
Destroy()
EndInterface
 
Structure OO_Structure ; The *VTable structure
Get.i
Set.i
Destroy.i
EndStructure
 
Structure OO_Var
*VirtualTable.OO_Structure
Value.i
EndStructure
 
Procedure OO_Get(*Self.OO_Var)
ProcedureReturn *Self\Value
EndProcedure
 
Procedure OO_Set(*Self.OO_Var, n)
*Self\Value = n
EndProcedure
 
Procedure CreateSingleton()
If TrySemaphore(SingletonSemaphore)
*p.OO_Var = AllocateMemory(SizeOf(OO_Var))
If *p
*p\VirtualTable = ?VTable
EndIf
EndIf
ProcedureReturn *p
EndProcedure
 
Procedure OO_Destroy(*Self.OO_Var)
FreeMemory(*Self)
SignalSemaphore(SingletonSemaphore)
EndProcedure
 
DataSection
VTable:
Data.i @OO_Get()
Data.i @OO_Set()
Data.i @OO_Destroy()
EndDataSection</syntaxhighlight>
====Simple OOP extension====
Using the open-source precompiler [http://www.development-lounge.de/viewtopic.php?t=5915 SimpleOOP].
<syntaxhighlight lang="purebasic">Singleton Class Demo
BeginPrivate
Name$
X.i
EndPrivate
Public Method Init(Name$)
This\Name$ = Name$
EndMethod
Public Method GetX()
MethodReturn This\X
EndMethod
Public Method SetX(n)
This\X = n
EndMethod
Public Method Hello()
MessageRequester("Hello!", "I'm "+This\Name$)
EndMethod
EndClass</syntaxhighlight>
 
=={{header|C}}==
Line 687 ⟶ 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 732 ⟶ 917:
 
static singleton = new Singleton();</syntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
type Singleton
model
text greeting
fun speak = void by block do writeLine(me.greeting + " I'm a singleton") end
end
Singleton instance
fun getInstance = Singleton by block
if instance == null do instance = Singleton() end
return instance
end
type SomeOtherType
Singleton s1 = Singleton.getInstance()
s1.greeting = "Hello"
Singleton s2 = Singleton.getInstance()
s2.greeting.append(", World!")
writeLine(s1 + " and " + s2 + " are the same object: " + (s1 == s2) + ", s2: " + s2.greeting)
s1.speak() # call instance method
</syntaxhighlight>
{{out}}
<pre>
§(0x02bf8098) and §(0x02bf8098) are the same object: ⊤, s2: Hello, World!
Hello, World! I'm a singleton
</pre>
 
=={{header|Epoxy}}==
Line 832 ⟶ 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 863 ⟶ 1,074:
s2 printa \ => 4
</syntaxhighlight>
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
REM Sacado del forum de FreeBASIC (https://www.freebasic.net/forum/viewtopic.php?t=20432)
 
Type singleton
Public :
Declare Static Function crearInstancia() As singleton Ptr
Declare Destructor ()
Dim i As Integer
Private :
Declare Constructor()
Declare Constructor(Byref rhs As singleton)
Declare Static Function instancia(Byval crear As Integer) As singleton Ptr
End Type
 
Static Function singleton.crearInstancia() As singleton Ptr
Return singleton.instancia(1)
End Function
 
Static Function singleton.instancia(Byval crear As Integer) As singleton Ptr
Static ref As singleton Ptr = 0
Function = 0
If crear = 0 Then
ref = 0
Elseif ref = 0 Then
ref = New singleton
Function = ref
End If
End Function
 
Constructor singleton ()
End Constructor
 
Destructor singleton()
singleton.instancia(0)
End Destructor
 
'-----------------------------------------------------------------------------
Dim As singleton Ptr ps1 = singleton.crearinstancia()
ps1->i = 1234
Print ps1, ps1->i
 
Dim As singleton Ptr ps2 = singleton.crearinstancia()
Print ps2
 
Delete ps1
 
Dim As singleton Ptr ps3 = singleton.crearinstancia()
Print ps3, ps3->i
Delete ps3
Sleep
</syntaxhighlight>
{{out}}
<pre>
2038352 1234
0
2038352 0
</pre>
 
 
=={{header|Go}}==
Line 1,186 ⟶ 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 1,260 ⟶ 1,428:
I am a singleton
</pre>
=={{header|M2000 Interpreter}}==
 
<syntaxhighlight lang="m2000 interpreter">
Module CheckSingleton {
\\ singleton
\\ pointers and static groups are the same object because
\\ each one has a pointer to same state (a tuple)
\\ but from outside we do the miracle to have a static group to act as a pointer
\\ We need a lambda function to hold the pointer to Singleton as closure
Global One=lambda M=pointer() (aValue=0)-> {
If M is type null then
\\ one time happen
Group Singleton {
Type:One
Private:
state=(aValue,)
Public:
module Add (x) {
.state+=x
}
Set {Drop}
Value {
=.state#val(0)
}
}
M->group(Singleton)
end if
\\ return M which is a pointer
=M
}
K=One(100)
Print Eval(K)=100
M=One()
Print Eval(M)=100
Print K is M = true
Print K is type One = true
K=>add 500
Print eval(K)=600
\\ copy K to Z (no pointer to Z, Z is named group)
Z=Group(K)
Print eval(z)=600, z=600
Z.add 1000
Print Z=1600, Eval(M)=1600, Eval(K)=1600
\\ push a copy of Z, but state is pointer so we get a copy of a pointer
Push Group(Z)
Read beta
Beta.add 1000
Print Z=2600, Eval(M)=2600, Eval(K)=2600
\\ convert pointer to group (a copy of group)
group delta=One()
delta.add 1000
Print Z=3600, beta=3600, delta=3600, Eval(M)=3600, Eval(K)=3600
\\ M and K are pointers to groups
M=>add 400
Print Z=4000, beta=4000, delta=4000, Eval(M)=4000, Eval(K)=4000
}
CheckSingleton
</syntaxhighlight>
 
 
=={{header|Lasso}}==
Line 1,674 ⟶ 1,901:
::attribute foo
</syntaxhighlight>
 
=={{header|OxygenBasic}}==
 
<syntaxhighlight lang="oxygenbasic">
Class Singleton
static sys inst 'private
int instantiated() { return inst }
void constructor(){ if not inst then inst=@this }
'all other methods start with @this=inst
end class
 
 
'if not singleton.instantiated
new Singleton MySingleton
'endif
</syntaxhighlight>
 
=={{header|Oz}}==
Line 1,828 ⟶ 2,038:
This is method 2 on +Singleton
-> +Singleton</pre>
 
=={{header|PureBasic}}==
===Native version===
Thread safe version.
<syntaxhighlight lang="purebasic">Global SingletonSemaphore=CreateSemaphore(1)
 
Interface OO_Interface ; Interface for any value of this type
Get.i()
Set(Value.i)
Destroy()
EndInterface
 
Structure OO_Structure ; The *VTable structure
Get.i
Set.i
Destroy.i
EndStructure
 
Structure OO_Var
*VirtualTable.OO_Structure
Value.i
EndStructure
 
Procedure OO_Get(*Self.OO_Var)
ProcedureReturn *Self\Value
EndProcedure
 
Procedure OO_Set(*Self.OO_Var, n)
*Self\Value = n
EndProcedure
 
Procedure CreateSingleton()
If TrySemaphore(SingletonSemaphore)
*p.OO_Var = AllocateMemory(SizeOf(OO_Var))
If *p
*p\VirtualTable = ?VTable
EndIf
EndIf
ProcedureReturn *p
EndProcedure
 
Procedure OO_Destroy(*Self.OO_Var)
FreeMemory(*Self)
SignalSemaphore(SingletonSemaphore)
EndProcedure
 
DataSection
VTable:
Data.i @OO_Get()
Data.i @OO_Set()
Data.i @OO_Destroy()
EndDataSection</syntaxhighlight>
===Simple OOP extension===
Using the open-source precompiler [http://www.development-lounge.de/viewtopic.php?t=5915 SimpleOOP].
<syntaxhighlight lang="purebasic">Singleton Class Demo
BeginPrivate
Name$
X.i
EndPrivate
Public Method Init(Name$)
This\Name$ = Name$
EndMethod
Public Method GetX()
MethodReturn This\X
EndMethod
Public Method SetX(n)
This\X = n
EndMethod
Public Method Hello()
MessageRequester("Hello!", "I'm "+This\Name$)
EndMethod
EndClass</syntaxhighlight>
 
=={{header|Python}}==
Line 2,156 ⟶ 2,289:
I am a singleton
</pre>
 
=={{header|TXR}}==
 
<syntaxhighlight lang="txrlisp">;; Custom (:singleton) clause which adds behavior to a class
;; asserting against multiple instantiation.
(define-struct-clause :singleton ()
^((:static inst-count 0)
(:postinit (me)
(assert (<= (inc me.inst-count) 1)))))
 
(defstruct singleton-one ()
(:singleton)
(:method speak (me)
(put-line "I am singleton-one")))
 
(defstruct singleton-two ()
(:singleton)
(:method speak (me)
(put-line "I am singleton-two")))
 
;; Test
 
;; Global singleton
(defvarl s1 (new singleton-one))
 
;; Local singleton in function (like static in C)
;; load-time evaluates once.
(defun fn ()
(let ((s2 (load-time (new singleton-two))))
s2.(speak)))
 
s1.(speak)
(fn) ;; multiple calls to fn don't re-instantiate singleton-two
(fn)
(put-line "so far, so good")
(new singleton-two) ;; assertion gooes off</syntaxhighlight>
 
{{out}}
 
<pre>I am singleton-one
I am singleton-two
I am singleton-two
so far, so good
txr: unhandled exception of type assert:
txr: assertion (<= (inc me.inst-count)
1) failed in singleton.tl:6
 
txr: during evaluation at singleton.tl:6 of form (sys:rt-assert-fail "singleton.tl"
6 '(<= (inc me.inst-count)
1))</pre>
 
=={{header|Vala}}==
Line 2,187 ⟶ 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 }
Line 2,229 ⟶ 2,412:
{{omit from|Mathematica}}
{{omit from|Maxima}}
{{omit from|Minimal BASIC|Does not have user-defined data structures or objects.}}
{{omit from|Metafont}}
{{omit from|Nascom BASIC|Does not have user-defined data structures or objects.}}
{{omit from|OCaml}}
{{omit from|Octave}}
{{omit from|Palo Alto Tiny BASIC|Does not have user-defined data structures or objects.}}
{{omit from|PARI/GP}}
{{omit from|PL/0|Does not have user-defined data structures or objects.}}
{{omit from|plainTeX}}
{{omit from|Retro|No OOP}}
Line 2,238 ⟶ 2,425:
{{omit from|TI-83 BASIC}}
{{omit from|TI-89 BASIC|Does not have user-defined data structures or objects.}}
{{omit from|Tiny BASIC|Does not have user-defined data structures or objects.}}
{{omit from|x86 Assembly}}
{{omit from|Z80 Assembly}}
162

edits