Singleton: Difference between revisions

2,751 bytes added ,  23 days ago
Add Ecstasy example
No edit summary
(Add Ecstasy example)
 
(7 intermediate revisions by 6 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,733 ⟶ 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,887 ⟶ 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,247 ⟶ 2,321:
 
s1.(speak)
(fn) ;; multiple calls to fn don't re-instantiate singeltonsingleton-two
(fn)
(put-line "so far, so good")
Line 2,296 ⟶ 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,338 ⟶ 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,347 ⟶ 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