Singleton: Difference between revisions
Content added Content deleted
(Added Epoxy) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 6: | Line 6: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">package |
||
{ |
{ |
||
public class Singleton |
public class Singleton |
||
Line 25: | Line 25: | ||
} |
} |
||
internal class SingletonEnforcer {}</ |
internal class SingletonEnforcer {}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
===Non Thread Safe=== |
===Non Thread Safe=== |
||
< |
<syntaxhighlight lang="ada">package Global_Singleton is |
||
procedure Set_Data (Value : Integer); |
procedure Set_Data (Value : Integer); |
||
function Get_Data return Integer; |
function Get_Data return Integer; |
||
Line 38: | Line 38: | ||
end record; |
end record; |
||
Instance : Instance_Type; |
Instance : Instance_Type; |
||
end Global_Singleton;</ |
end Global_Singleton;</syntaxhighlight> |
||
< |
<syntaxhighlight lang="ada">package body Global_Singleton is |
||
-------------- |
-------------- |
||
Line 60: | Line 60: | ||
end Get_Data; |
end Get_Data; |
||
end Global_Singleton;</ |
end Global_Singleton;</syntaxhighlight> |
||
===Thread Safe=== |
===Thread Safe=== |
||
< |
<syntaxhighlight lang="ada">package Protected_Singleton is |
||
procedure Set_Data (Value : Integer); |
procedure Set_Data (Value : Integer); |
||
function Get_Data return Integer; |
function Get_Data return Integer; |
||
Line 73: | Line 73: | ||
Data : Integer := 0; |
Data : Integer := 0; |
||
end Instance_Type; |
end Instance_Type; |
||
end Protected_Singleton;</ |
end Protected_Singleton;</syntaxhighlight> |
||
< |
<syntaxhighlight lang="ada">package body Protected_Singleton is |
||
-------------- |
-------------- |
||
Line 121: | Line 121: | ||
end Instance; |
end Instance; |
||
end Protected_Singleton;</ |
end Protected_Singleton;</syntaxhighlight> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
{{works with | AutoHotkey_L}} |
{{works with | AutoHotkey_L}} |
||
Translation of python borg pattern |
Translation of python borg pattern |
||
< |
<syntaxhighlight lang="autohotkey">b1 := borg() |
||
b2 := borg() |
b2 := borg() |
||
msgbox % "b1 is b2? " . (b1 == b2) |
msgbox % "b1 is b2? " . (b1 == b2) |
||
Line 153: | Line 153: | ||
brg[1, name] := val |
brg[1, name] := val |
||
Return val |
Return val |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
Since C doesn't really support classes anyhow, there's not much to do. If you want somethin akin to a singleton, what you do is first declare the interface functions in a header (.h) file. |
Since C doesn't really support classes anyhow, there's not much to do. If you want somethin akin to a singleton, what you do is first declare the interface functions in a header (.h) file. |
||
< |
<syntaxhighlight lang="c">#ifndef SILLY_H |
||
#define SILLY_H |
#define SILLY_H |
||
Line 163: | Line 163: | ||
extern int PlayFetchWithDog( float weightOfStick); |
extern int PlayFetchWithDog( float weightOfStick); |
||
#endif</ |
#endif</syntaxhighlight> |
||
Then in a separate C source (.c) file, define your structures, variables and functions. |
Then in a separate C source (.c) file, define your structures, variables and functions. |
||
< |
<syntaxhighlight lang="c">... |
||
#include "silly.h" |
#include "silly.h" |
||
Line 189: | Line 189: | ||
{ ... |
{ ... |
||
if(weightOfStick < lazyDog.max_stick_weight){... |
if(weightOfStick < lazyDog.max_stick_weight){... |
||
}</ |
}</syntaxhighlight> |
||
Code using the singleton includes the header and cannot create a |
Code using the singleton includes the header and cannot create a |
||
struct sDog as the definition is only in the C source (or other header privately included by the silly.c source). Only the functions declared in the header may be used externally. |
struct sDog as the definition is only in the C source (or other header privately included by the silly.c source). Only the functions declared in the header may be used externally. |
||
< |
<syntaxhighlight lang="c">... |
||
#include "silly.h" |
#include "silly.h" |
||
... |
... |
||
Line 198: | Line 198: | ||
JumpOverTheDog( 4); |
JumpOverTheDog( 4); |
||
retrieved = PlayFetchWithDog( 3.1); |
retrieved = PlayFetchWithDog( 3.1); |
||
...</ |
...</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
Line 204: | Line 204: | ||
Performance suffers because the lock is acquired every time Instance is accessed.<br /> |
Performance suffers because the lock is acquired every time Instance is accessed.<br /> |
||
This implementation is extremely slow and should not be used (but is seen often). |
This implementation is extremely slow and should not be used (but is seen often). |
||
< |
<syntaxhighlight lang="csharp">public sealed class Singleton1 //Lazy: Yes ||| Thread-safe: Yes ||| Uses locking: Yes |
||
{ |
{ |
||
private static Singleton1 instance; |
private static Singleton1 instance; |
||
Line 219: | Line 219: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Fixes excessive locking by double-checking for null.=== |
===Fixes excessive locking by double-checking for null.=== |
||
Still uses locking and implementation is ugly and verbose. |
Still uses locking and implementation is ugly and verbose. |
||
< |
<syntaxhighlight lang="csharp">public sealed class Singleton2 //Lazy: Yes ||| Thread-safe: Yes ||| Uses locking: Yes, but only once |
||
{ |
{ |
||
private static Singleton2 instance; |
private static Singleton2 instance; |
||
Line 240: | Line 240: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Really simple implementation without locking.=== |
===Really simple implementation without locking.=== |
||
It still is not completely lazy. If there are other static members, accessing any of those will still cause initialization. |
It still is not completely lazy. If there are other static members, accessing any of those will still cause initialization. |
||
< |
<syntaxhighlight lang="csharp">public sealed class Singleton3 //Lazy: Yes, but not completely ||| Thread-safe: Yes ||| Uses locking: No |
||
{ |
{ |
||
private static Singleton3 Instance { get; } = new Singleton3(); |
private static Singleton3 Instance { get; } = new Singleton3(); |
||
static Singleton3() { } |
static Singleton3() { } |
||
}</ |
}</syntaxhighlight> |
||
===Truly lazy by using an inner class.=== |
===Truly lazy by using an inner class.=== |
||
This version is completely lazy but the code looks more complicated than it needs to be. |
This version is completely lazy but the code looks more complicated than it needs to be. |
||
< |
<syntaxhighlight lang="csharp">public sealed class Singleton4 //Lazy: Yes ||| Thread-safe: Yes ||| Uses locking: No |
||
{ |
{ |
||
public static Singleton4 Instance => SingletonHolder.instance; |
public static Singleton4 Instance => SingletonHolder.instance; |
||
Line 263: | Line 263: | ||
internal static readonly Singleton4 instance = new Singleton4(); |
internal static readonly Singleton4 instance = new Singleton4(); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Using Lazy<T>=== |
===Using Lazy<T>=== |
||
C# has a dedicated type for lazy initialization: Lazy<T>.<br /> |
C# has a dedicated type for lazy initialization: Lazy<T>.<br /> |
||
It makes implementing a Singleton really easy. Recommended. |
It makes implementing a Singleton really easy. Recommended. |
||
< |
<syntaxhighlight lang="csharp">public sealed class Singleton5 //Lazy: Yes ||| Thread-safe: Yes ||| Uses locking: No |
||
{ |
{ |
||
private static readonly Lazy<Singleton5> lazy = new Lazy<Singleton5>(() => new Singleton5()); |
private static readonly Lazy<Singleton5> lazy = new Lazy<Singleton5>(() => new Singleton5()); |
||
public static Singleton5 Instance => lazy.Value; |
public static Singleton5 Instance => lazy.Value; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
A generic singleton template class (implemented via the "Curiously Recurring Template Pattern"[https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern]). Warning: if using a version of C++ prior to C++11, a [[Mutex#C|mutex]] (or similar) is required to access static variables within a multi-threaded program. |
A generic singleton template class (implemented via the "Curiously Recurring Template Pattern"[https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern]). Warning: if using a version of C++ prior to C++11, a [[Mutex#C|mutex]] (or similar) is required to access static variables within a multi-threaded program. |
||
< |
<syntaxhighlight lang="cpp"> |
||
#include <stdexcept> |
#include <stdexcept> |
||
Line 378: | Line 378: | ||
controller::instance().work(); |
controller::instance().work(); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Caché ObjectScript}}== |
=={{header|Caché ObjectScript}}== |
||
Line 384: | Line 384: | ||
In Caché, each job runs in a self-contained execution environment (i.e. a separate process instead of a thread). However, it is possible for each process to share data through multidimensional storage (global variables). This is because when the Caché virtual machine starts, it allocates a single, large chunk of shared memory to allow all Caché processes to access this data simultaneously. However, it is the responsibility of the application developer to ensure read and write access to objects is properly co-ordinated (or 'synchronized') between processes to prevent concurrency problems. Also, Caché defines any global variable whose name starts with 'CacheTemp' as being temporary, which means changes are not usually written to disk and are instead maintained within the in-memory buffer pool. |
In Caché, each job runs in a self-contained execution environment (i.e. a separate process instead of a thread). However, it is possible for each process to share data through multidimensional storage (global variables). This is because when the Caché virtual machine starts, it allocates a single, large chunk of shared memory to allow all Caché processes to access this data simultaneously. However, it is the responsibility of the application developer to ensure read and write access to objects is properly co-ordinated (or 'synchronized') between processes to prevent concurrency problems. Also, Caché defines any global variable whose name starts with 'CacheTemp' as being temporary, which means changes are not usually written to disk and are instead maintained within the in-memory buffer pool. |
||
< |
<syntaxhighlight lang="cos"> |
||
/// The <CLASS>Singleton</CLASS> class represents a global singleton object that can |
/// The <CLASS>Singleton</CLASS> class represents a global singleton object that can |
||
/// be instantiated by multiple processes. The 'Get' class method is used to obtain |
/// be instantiated by multiple processes. The 'Get' class method is used to obtain |
||
Line 516: | Line 516: | ||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out|Examples}} |
{{out|Examples}} |
||
Line 530: | Line 530: | ||
For a simple example, the following program constructs English sentences without worrying about extra space occurring at points where no text (<code>the-empty-phrase</code>, our singleton) is inserted. |
For a simple example, the following program constructs English sentences without worrying about extra space occurring at points where no text (<code>the-empty-phrase</code>, our singleton) is inserted. |
||
< |
<syntaxhighlight lang="lisp">(defgeneric concat (a b) |
||
(:documentation "Concatenate two phrases.")) |
(:documentation "Concatenate two phrases.")) |
||
Line 553: | Line 553: | ||
(dolist (q (list 'the-empty-phrase |
(dolist (q (list 'the-empty-phrase |
||
(make-instance 'nonempty-phrase :text "up the hill"))) |
(make-instance 'nonempty-phrase :text "up the hill"))) |
||
(write-line (text (reduce #'concat (list before p mid q after))))))))</ |
(write-line (text (reduce #'concat (list before p mid q after))))))))</syntaxhighlight> |
||
Thread safety is irrelevant since the singleton is created at load time, not first access. |
Thread safety is irrelevant since the singleton is created at load time, not first access. |
||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">module singleton ; |
||
import std.stdio ; |
import std.stdio ; |
||
import std.thread ; |
import std.thread ; |
||
Line 617: | Line 617: | ||
x.wait ; y.wait ; z.wait ; |
x.wait ; y.wait ; z.wait ; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>>>Mary come in. |
<pre>>>Mary come in. |
||
Line 641: | Line 641: | ||
=={{header|Delphi}} and {{header|Pascal}}== |
=={{header|Delphi}} and {{header|Pascal}}== |
||
Detailed explanation [http://www.yanniel.info/2010/10/singleton-pattern-delphi.html here]. (Delphi started out as an object-oriented version of Pascal.) |
Detailed explanation [http://www.yanniel.info/2010/10/singleton-pattern-delphi.html here]. (Delphi started out as an object-oriented version of Pascal.) |
||
< |
<syntaxhighlight lang="delphi">unit Singleton; |
||
interface |
interface |
||
Line 680: | Line 680: | ||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|E}}== |
=={{header|E}}== |
||
Since E uses closure-style objects rather than classes, a singleton is simply an object which is defined at the top level of the program, not inside any method. There are no thread-safety issues since the singleton, like every other object, belongs to some particular [http://www.erights.org/elib/concurrency/vat.html vat] (but can be remotely invoked from other vats). |
Since E uses closure-style objects rather than classes, a singleton is simply an object which is defined at the top level of the program, not inside any method. There are no thread-safety issues since the singleton, like every other object, belongs to some particular [http://www.erights.org/elib/concurrency/vat.html vat] (but can be remotely invoked from other vats). |
||
< |
<syntaxhighlight lang="e">def aSingleton { |
||
# ... |
# ... |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
Line 693: | Line 693: | ||
'''Implementation:''' |
'''Implementation:''' |
||
< |
<syntaxhighlight lang="eiffel">class |
||
SINGLETON |
SINGLETON |
||
create {SINGLETON_ACCESS} |
create {SINGLETON_ACCESS} |
||
Line 699: | Line 699: | ||
feature |
feature |
||
-- singleton features go here |
-- singleton features go here |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="eiffel">frozen class |
||
SINGLETON_ACCESS |
SINGLETON_ACCESS |
||
feature |
feature |
||
Line 709: | Line 709: | ||
Result /= Void |
Result /= Void |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
'''Usage:''' |
'''Usage:''' |
||
< |
<syntaxhighlight lang="eiffel">s: SINGLETON -- declaration somewhere |
||
s := (create{SINGLETON_ACCESS}).singleton -- in some routine</ |
s := (create{SINGLETON_ACCESS}).singleton -- in some routine</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
Stateless singleton |
Stateless singleton |
||
< |
<syntaxhighlight lang="elena"> |
||
singleton Singleton |
singleton Singleton |
||
{ |
{ |
||
// ... |
// ... |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Normal singleton |
Normal singleton |
||
< |
<syntaxhighlight lang="elena">class Singleton |
||
{ |
{ |
||
object theField; |
object theField; |
||
Line 731: | Line 731: | ||
} |
} |
||
static singleton = new Singleton();</ |
static singleton = new Singleton();</syntaxhighlight> |
||
=={{header|Epoxy}}== |
=={{header|Epoxy}}== |
||
< |
<syntaxhighlight lang="epoxy">fn Singleton() |
||
if this.self then return this.self cls |
if this.self then return this.self cls |
||
var new: {} |
var new: {} |
||
Line 757: | Line 757: | ||
NewSingleton>>setName("Test") |
NewSingleton>>setName("Test") |
||
log(MySingleton.name) --Test</ |
log(MySingleton.name) --Test</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 767: | Line 767: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Erlang is not object-oriented, so there is no such thing as a singleton class. The singleton is something of an anti-pattern in Erlang, so if you are tempted to do this, there is probably a better architecture. If you do want something akin to a singleton, you start and register a process that maintains its state in a message loop and provides its state to anyone that wants it or needs to change it. Since this is done with message passing, it's safe for concurrent use. |
Erlang is not object-oriented, so there is no such thing as a singleton class. The singleton is something of an anti-pattern in Erlang, so if you are tempted to do this, there is probably a better architecture. If you do want something akin to a singleton, you start and register a process that maintains its state in a message loop and provides its state to anyone that wants it or needs to change it. Since this is done with message passing, it's safe for concurrent use. |
||
< |
<syntaxhighlight lang="erlang">-module(singleton). |
||
-export([get/0, set/1, start/0]). |
-export([get/0, set/1, start/0]). |
||
Line 799: | Line 799: | ||
From ! ok, |
From ! ok, |
||
loop(NewValue) |
loop(NewValue) |
||
end.</ |
end.</syntaxhighlight> |
||
Here is an example of how to use it (from the shell). It assumes singleton:start/0 was already called from the supervisor tree (as would be typical if you were using something like this). |
Here is an example of how to use it (from the shell). It assumes singleton:start/0 was already called from the supervisor tree (as would be typical if you were using something like this). |
||
< |
<syntaxhighlight lang="erlang">1> singleton:get(). |
||
not_set |
not_set |
||
2> singleton:set(apple). |
2> singleton:set(apple). |
||
Line 816: | Line 816: | ||
ok |
ok |
||
7> singleton:get(). |
7> singleton:get(). |
||
{ok,42}</ |
{ok,42}</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: classes.singleton kernel io prettyprint ; |
||
IN: singleton-demo |
IN: singleton-demo |
||
SINGLETON: bar |
SINGLETON: bar |
||
GENERIC: foo ( obj -- ) |
GENERIC: foo ( obj -- ) |
||
M: bar foo drop "Hello!" print ;</ |
M: bar foo drop "Hello!" print ;</syntaxhighlight> |
||
( scratchpad ) bar foo |
( scratchpad ) bar foo |
||
Hello! |
Hello! |
||
Line 834: | Line 834: | ||
Needs the FMS-SI (single inheritance) library code located here: |
Needs the FMS-SI (single inheritance) library code located here: |
||
http://soton.mpeforth.com/flag/fms/index.html |
http://soton.mpeforth.com/flag/fms/index.html |
||
< |
<syntaxhighlight lang="forth">include FMS-SI.f |
||
\ A singleton is created by using normal Forth data |
\ A singleton is created by using normal Forth data |
||
Line 862: | Line 862: | ||
s1 printb \ => 9 |
s1 printb \ => 9 |
||
s2 printa \ => 4 |
s2 printa \ => 4 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic"> |
||
REM Sacado del forum de FreeBASIC (https://www.freebasic.net/forum/viewtopic.php?t=20432) |
REM Sacado del forum de FreeBASIC (https://www.freebasic.net/forum/viewtopic.php?t=20432) |
||
Line 916: | Line 916: | ||
Delete ps3 |
Delete ps3 |
||
Sleep |
Sleep |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 929: | Line 929: | ||
From the Go standard library, sync.Once provides a way to ensure that some "step," effectively an initialization step, is performed no more than once even if it might be attempted from multiple concurrent goroutines. This capability might be considered similar to some mechanism ensuring that singleton constructor code is only run once. |
From the Go standard library, sync.Once provides a way to ensure that some "step," effectively an initialization step, is performed no more than once even if it might be attempted from multiple concurrent goroutines. This capability might be considered similar to some mechanism ensuring that singleton constructor code is only run once. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 959: | Line 959: | ||
w.Wait() |
w.Wait() |
||
log.Println("after trying both, instance =", instance) |
log.Println("after trying both, instance =", instance) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 974: | Line 974: | ||
Because packages cannot be imported multiple times, data declared at package level will only ever have a single instance, and the package as a whole serves as a singleton. |
Because packages cannot be imported multiple times, data declared at package level will only ever have a single instance, and the package as a whole serves as a singleton. |
||
< |
<syntaxhighlight lang="go">package singlep |
||
// package level data declarations serve as singleton instance variables |
// package level data declarations serve as singleton instance variables |
||
Line 987: | Line 987: | ||
func F() int { |
func F() int { |
||
return Y - X |
return Y - X |
||
}</ |
}</syntaxhighlight> |
||
Example program using the package: |
Example program using the package: |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,000: | Line 1,000: | ||
fmt.Println(singlep.X, singlep.Y) |
fmt.Println(singlep.X, singlep.Y) |
||
fmt.Println(singlep.F()) |
fmt.Println(singlep.F()) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,011: | Line 1,011: | ||
This example combines the two previous concepts and also shows some additional concepts. It has packages imported with a "diamond" dependency. While both <code>red</code> and <code>blue</code> import <code>single</code>, only a single variable <code>color</code> will exist in memory. The <code>init()</code> mechanism shown above actually runs before <code>main()</code>. In contrast, the <code>sync.Once</code> mechanism can serve as constructor code after <code>main()</code> begins. |
This example combines the two previous concepts and also shows some additional concepts. It has packages imported with a "diamond" dependency. While both <code>red</code> and <code>blue</code> import <code>single</code>, only a single variable <code>color</code> will exist in memory. The <code>init()</code> mechanism shown above actually runs before <code>main()</code>. In contrast, the <code>sync.Once</code> mechanism can serve as constructor code after <code>main()</code> begins. |
||
< |
<syntaxhighlight lang="go">package single |
||
import ( |
import ( |
||
Line 1,034: | Line 1,034: | ||
once.Do(func() { color = c }) |
once.Do(func() { color = c }) |
||
log.Println("color initialized to", color) |
log.Println("color initialized to", color) |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="go">package red |
||
import ( |
import ( |
||
Line 1,046: | Line 1,046: | ||
log.Println("trying to set red") |
log.Println("trying to set red") |
||
single.SetColor("red") |
single.SetColor("red") |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="go">package blue |
||
import ( |
import ( |
||
Line 1,058: | Line 1,058: | ||
log.Println("trying to set blue") |
log.Println("trying to set blue") |
||
single.SetColor("blue") |
single.SetColor("blue") |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,082: | Line 1,082: | ||
} |
} |
||
log.Println(single.Color()) |
log.Println(single.Color()) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,095: | Line 1,095: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<syntaxhighlight lang="groovy">@Singleton |
||
class SingletonClass { |
class SingletonClass { |
||
Line 1,105: | Line 1,105: | ||
SingletonClass.instance.invokeMe() |
SingletonClass.instance.invokeMe() |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>invoking method of a singleton class</pre> |
<pre>invoking method of a singleton class</pre> |
||
Line 1,111: | Line 1,111: | ||
==Icon and {{header|Unicon}}== |
==Icon and {{header|Unicon}}== |
||
Icon is not object oriented, but Unicon supports O-O programming. |
Icon is not object oriented, but Unicon supports O-O programming. |
||
< |
<syntaxhighlight lang="unicon">class Singleton |
||
method print() |
method print() |
||
write("Hi there.") |
write("Hi there.") |
||
Line 1,123: | Line 1,123: | ||
Singleton().print() |
Singleton().print() |
||
Singleton().print() |
Singleton().print() |
||
end</ |
end</syntaxhighlight> |
||
This Unicon example uses a number of Icon features. |
This Unicon example uses a number of Icon features. |
||
Line 1,135: | Line 1,135: | ||
=={{header|Io}}== |
=={{header|Io}}== |
||
Io does not have globals. But it is easy to make singleton objects: |
Io does not have globals. But it is easy to make singleton objects: |
||
< |
<syntaxhighlight lang="io">Singleton := Object clone |
||
Singleton clone = Singleton</ |
Singleton clone = Singleton</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 1,146: | Line 1,146: | ||
===Thread-safe=== |
===Thread-safe=== |
||
[[wp:Double-checked locking]]; only use with Java 1.5+ |
[[wp:Double-checked locking]]; only use with Java 1.5+ |
||
< |
<syntaxhighlight lang="java">class Singleton |
||
{ |
{ |
||
private static Singleton myInstance; |
private static Singleton myInstance; |
||
Line 1,171: | Line 1,171: | ||
// Any other methods |
// Any other methods |
||
}</ |
}</syntaxhighlight> |
||
===Thread-Safe Lazy-Loaded=== |
===Thread-Safe Lazy-Loaded=== |
||
This is the [[wp:Initialization-on-demand holder idiom]]. |
This is the [[wp:Initialization-on-demand holder idiom]]. |
||
< |
<syntaxhighlight lang="java">public class Singleton { |
||
private Singleton() { |
private Singleton() { |
||
// Constructor code goes here. |
// Constructor code goes here. |
||
Line 1,187: | Line 1,187: | ||
return LazyHolder.INSTANCE; |
return LazyHolder.INSTANCE; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Non-Thread-Safe=== |
===Non-Thread-Safe=== |
||
< |
<syntaxhighlight lang="java">class Singleton |
||
{ |
{ |
||
private static Singleton myInstance; |
private static Singleton myInstance; |
||
Line 1,209: | Line 1,209: | ||
// Any other methods |
// Any other methods |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">function Singleton() { |
||
if(Singleton._instance) return Singleton._instance; |
if(Singleton._instance) return Singleton._instance; |
||
this.set(""); |
this.set(""); |
||
Line 1,231: | Line 1,231: | ||
c.append("!!!"); |
c.append("!!!"); |
||
document.write( (new Singleton()).get() );</ |
document.write( (new Singleton()).get() );</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Julia allows singletons as type declarations without further specifiers. There can be only one instance of such a type, and if more than one variable is bound to such a type they are actually all bound to the same instance in memory: |
Julia allows singletons as type declarations without further specifiers. There can be only one instance of such a type, and if more than one variable is bound to such a type they are actually all bound to the same instance in memory: |
||
< |
<syntaxhighlight lang="julia"> |
||
struct IAmaSingleton end |
struct IAmaSingleton end |
||
Line 1,242: | Line 1,242: | ||
println("x == y is $(x == y) and x === y is $(x === y).") |
println("x == y is $(x == y) and x === y is $(x === y).") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
Kotlin has built-in support for singletons via object declarations. To refer to the singleton, we simply use its name which can be any valid identifier other than a keyword: |
Kotlin has built-in support for singletons via object declarations. To refer to the singleton, we simply use its name which can be any valid identifier other than a keyword: |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
object Singleton { |
object Singleton { |
||
Line 1,254: | Line 1,254: | ||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Singleton.speak() |
Singleton.speak() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,267: | Line 1,267: | ||
===Server wide singleton=== |
===Server wide singleton=== |
||
< |
<syntaxhighlight lang="lasso">// Define the thread if it doesn't exist |
||
// New definition supersede any current threads. |
// New definition supersede any current threads. |
||
Line 1,283: | Line 1,283: | ||
#b->switch = 'b' |
#b->switch = 'b' |
||
#a->switch // b</ |
#a->switch // b</syntaxhighlight> |
||
===Thread level singleton=== |
===Thread level singleton=== |
||
< |
<syntaxhighlight lang="lasso">// Define thread level singleton |
||
define singleton => type { |
define singleton => type { |
||
Line 1,302: | Line 1,302: | ||
#b->switch = 'b' |
#b->switch = 'b' |
||
#a->switch // b</ |
#a->switch // b</syntaxhighlight> |
||
=={{header|Latitude}}== |
=={{header|Latitude}}== |
||
Latitude objects are prototypes, so any new object can be treated as a singleton by simply not cloning it. For added security, one can always override <code>clone</code> to make it clear that the object should not be cloned, but this is generally overkill. |
Latitude objects are prototypes, so any new object can be treated as a singleton by simply not cloning it. For added security, one can always override <code>clone</code> to make it clear that the object should not be cloned, but this is generally overkill. |
||
< |
<syntaxhighlight lang="latitude">Singleton ::= Object clone tap { |
||
self id := 0. |
self id := 0. |
||
self newID := { |
self newID := { |
||
Line 1,318: | Line 1,318: | ||
println: Singleton newID. ; 1 |
println: Singleton newID. ; 1 |
||
println: Singleton newID. ; 2 |
println: Singleton newID. ; 2 |
||
println: Singleton newID. ; 3</ |
println: Singleton newID. ; 3</syntaxhighlight> |
||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
In Lingo a Singleton class can be implemented like this: |
In Lingo a Singleton class can be implemented like this: |
||
< |
<syntaxhighlight lang="lingo">-- parent script "SingletonDemo" |
||
property _instance |
property _instance |
||
Line 1,343: | Line 1,343: | ||
me._someProperty = me._someProperty + x |
me._someProperty = me._someProperty + x |
||
return me._someProperty |
return me._someProperty |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Logtalk}}== |
=={{header|Logtalk}}== |
||
Logtalk supports both classes and prototypes. A prototype is a much simpler solution for defining a singleton object than defining a class with only an instance. |
Logtalk supports both classes and prototypes. A prototype is a much simpler solution for defining a singleton object than defining a class with only an instance. |
||
< |
<syntaxhighlight lang="logtalk">:- object(singleton). |
||
:- public(value/1). |
:- public(value/1). |
||
Line 1,362: | Line 1,362: | ||
state(0). |
state(0). |
||
:- end_object.</ |
:- end_object.</syntaxhighlight> |
||
A simple usage example after compiling and loading the code above: |
A simple usage example after compiling and loading the code above: |
||
< |
<syntaxhighlight lang="logtalk">| ?- singleton::value(Value). |
||
Value = 0 |
Value = 0 |
||
yes |
yes |
||
Line 1,370: | Line 1,370: | ||
| ?- singleton::(set_value(1), value(Value)). |
| ?- singleton::(set_value(1), value(Value)). |
||
Value = 1 |
Value = 1 |
||
yes</ |
yes</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
Uses a static field to avoid synchronization problems and the ''flawed'' "double-checked locking" idiom in JVMs. See [http://www.ibm.com/developerworks/java/library/j-dcl/index.html www.ibm.com/developerworks/java/library/j-dcl/index.html] for a detailed explanation. |
Uses a static field to avoid synchronization problems and the ''flawed'' "double-checked locking" idiom in JVMs. See [http://www.ibm.com/developerworks/java/library/j-dcl/index.html www.ibm.com/developerworks/java/library/j-dcl/index.html] for a detailed explanation. |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols binary |
options replace format comments java crossref symbols binary |
||
Line 1,472: | Line 1,472: | ||
return info |
return info |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,502: | Line 1,502: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
In the file <code>singleton.nim</code> we don't export the type, so new objects can't be created: |
In the file <code>singleton.nim</code> we don't export the type, so new objects can't be created: |
||
< |
<syntaxhighlight lang="nim">type Singleton = object # Singleton* would export |
||
foo*: int |
foo*: int |
||
var single* = Singleton(foo: 0)</ |
var single* = Singleton(foo: 0)</syntaxhighlight> |
||
Then in another file we can use the singleton object: |
Then in another file we can use the singleton object: |
||
< |
<syntaxhighlight lang="nim">import singleton |
||
single.foo = 12 |
single.foo = 12 |
||
echo single.foo</ |
echo single.foo</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">class Singleton { |
||
@singleton : static : Singleton; |
@singleton : static : Singleton; |
||
Line 1,530: | Line 1,530: | ||
... |
... |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
===Non-Thread-Safe=== |
===Non-Thread-Safe=== |
||
(Using Cocoa/OpenStep's NSObject as a base class) |
(Using Cocoa/OpenStep's NSObject as a base class) |
||
< |
<syntaxhighlight lang="objc">// SomeSingleton.h |
||
@interface SomeSingleton : NSObject |
@interface SomeSingleton : NSObject |
||
{ |
{ |
||
Line 1,543: | Line 1,543: | ||
+ (SomeSingleton *)sharedInstance; |
+ (SomeSingleton *)sharedInstance; |
||
@end</ |
@end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="objc">// SomeSingleton.m |
||
@implementation SomeSingleton |
@implementation SomeSingleton |
||
Line 1,582: | Line 1,582: | ||
} |
} |
||
@end</ |
@end</syntaxhighlight> |
||
===Thread-Safe=== |
===Thread-Safe=== |
||
Same as above except: |
Same as above except: |
||
< |
<syntaxhighlight lang="objc">+ (SomeSingleton *) sharedInstance |
||
{ |
{ |
||
static SomeSingleton *sharedInstance = nil; |
static SomeSingleton *sharedInstance = nil; |
||
Line 1,595: | Line 1,595: | ||
} |
} |
||
return sharedInstance; |
return sharedInstance; |
||
}</ |
}</syntaxhighlight> |
||
===With GCD=== |
===With GCD=== |
||
Same as above except: |
Same as above except: |
||
< |
<syntaxhighlight lang="objc">+ (SomeSingleton *) sharedInstance |
||
{ |
{ |
||
static SomeSingleton *sharedInstance = nil; |
static SomeSingleton *sharedInstance = nil; |
||
Line 1,607: | Line 1,607: | ||
}); |
}); |
||
return sharedInstance; |
return sharedInstance; |
||
}</ |
}</syntaxhighlight> |
||
===With class methods=== |
===With class methods=== |
||
Line 1,624: | Line 1,624: | ||
For instance, this Sequence class creates instances that increment an integer and send it. If a task tries to get the next value before it is incremented, it will wait until the channel is no more empty and holds the new value. This won't work if the value is a mutable value (you will get an exception if you try to send a mutable object into channel). A mutable object can't be shared between tasks. Here we send a new integer each time. |
For instance, this Sequence class creates instances that increment an integer and send it. If a task tries to get the next value before it is incremented, it will wait until the channel is no more empty and holds the new value. This won't work if the value is a mutable value (you will get an exception if you try to send a mutable object into channel). A mutable object can't be shared between tasks. Here we send a new integer each time. |
||
< |
<syntaxhighlight lang="oforth">Object Class new: Sequence(channel) |
||
Sequence method: initialize(initialValue) |
Sequence method: initialize(initialValue) |
||
Channel newSize(1) := channel |
Channel newSize(1) := channel |
||
@channel send(initialValue) drop ; |
@channel send(initialValue) drop ; |
||
Sequence method: nextValue @channel receive dup 1 + @channel send drop ;</ |
Sequence method: nextValue @channel receive dup 1 + @channel send drop ;</syntaxhighlight> |
||
Usage : |
Usage : |
||
< |
<syntaxhighlight lang="oforth">import: parallel |
||
: testSequence |
: testSequence |
||
| s i | |
| s i | |
||
Sequence new(0) ->s |
Sequence new(0) ->s |
||
100 loop: i [ #[ s nextValue println ] & ] ;</ |
100 loop: i [ #[ s nextValue println ] & ] ;</syntaxhighlight> |
||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
a = .singleton~new |
a = .singleton~new |
||
b = .singleton~new |
b = .singleton~new |
||
Line 1,673: | Line 1,673: | ||
a singleton. |
a singleton. |
||
::attribute foo |
::attribute foo |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OxygenBasic}}== |
=={{header|OxygenBasic}}== |
||
< |
<syntaxhighlight lang="oxygenbasic"> |
||
Class Singleton |
Class Singleton |
||
static sys inst 'private |
static sys inst 'private |
||
Line 1,690: | Line 1,690: | ||
new Singleton MySingleton |
new Singleton MySingleton |
||
'endif |
'endif |
||
</ |
</syntaxhighlight> |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
Singleton is not a common pattern in Oz programs. It can be implemented by limiting the scope of the class definition such that only the <code>GetInstance</code> function has access to it. |
Singleton is not a common pattern in Oz programs. It can be implemented by limiting the scope of the class definition such that only the <code>GetInstance</code> function has access to it. |
||
< |
<syntaxhighlight lang="oz">declare |
||
local |
local |
||
class Singleton |
class Singleton |
||
Line 1,712: | Line 1,712: | ||
end |
end |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
This will work as long as all functors are linked with <code>import</code> statements. If you use multiple calls to <code>Module.link</code> instead, you will get multiple instances of the "Singleton". |
This will work as long as all functors are linked with <code>import</code> statements. If you use multiple calls to <code>Module.link</code> instead, you will get multiple instances of the "Singleton". |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">package Singleton; |
||
use strict; |
use strict; |
||
use warnings; |
use warnings; |
||
Line 1,744: | Line 1,744: | ||
my $s2 = Singleton->new; |
my $s2 = Singleton->new; |
||
printf "name: %s, ref: %s\n", $s2->name, $s2;</ |
printf "name: %s, ref: %s\n", $s2->name, $s2;</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Line 1,751: | Line 1,751: | ||
or keep check() private and invoke it internally from a few critical routines. |
or keep check() private and invoke it internally from a few critical routines. |
||
Needs 0.8.1+ |
Needs 0.8.1+ |
||
< |
<syntaxhighlight lang="phix">-- <separate include file> |
||
object chk = NULL |
object chk = NULL |
||
class singleton |
class singleton |
||
Line 1,769: | Line 1,769: | ||
s.check() |
s.check() |
||
--s2.check() -- dies</ |
--s2.check() -- dies</syntaxhighlight> |
||
While all classes are technically global in the sense that builtins\structs.e knows all about them, the |
While all classes are technically global in the sense that builtins\structs.e knows all about them, the |
||
implicit associated user defined type is by default private (ie w/o "global" in front of the class def). |
implicit associated user defined type is by default private (ie w/o "global" in front of the class def). |
||
Line 1,775: | Line 1,775: | ||
<code>class s = new("singleton")</code> could still be used anywhere, and that way get duplicates. |
<code>class s = new("singleton")</code> could still be used anywhere, and that way get duplicates. |
||
One obvious alternative (of no special merit imo) might be to replace that global singleton s with: |
One obvious alternative (of no special merit imo) might be to replace that global singleton s with: |
||
< |
<syntaxhighlight lang="phix">global function get_singleton() |
||
if chk==NULL then |
if chk==NULL then |
||
chk = new("singleton") |
chk = new("singleton") |
||
end if |
end if |
||
return chk |
return chk |
||
end function</ |
end function</syntaxhighlight> |
||
Technically, builtins/struct.e looks like it could easily be modified to support something very similar |
Technically, builtins/struct.e looks like it could easily be modified to support something very similar |
||
to the Python Borg pattern, by appropriately sharing cdx/tid in new(). However it would be even better |
to the Python Borg pattern, by appropriately sharing cdx/tid in new(). However it would be even better |
||
Line 1,788: | Line 1,788: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">class Singleton { |
||
protected static $instance = null; |
protected static $instance = null; |
||
public $test_var; |
public $test_var; |
||
Line 1,808: | Line 1,808: | ||
echo $bar->test_var; //Prints 'One' |
echo $bar->test_var; //Prints 'One' |
||
$fail = new Singleton(); //Fatal error</ |
$fail = new Singleton(); //Fatal error</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
As there is no physical difference between classes and objects, we can use the |
As there is no physical difference between classes and objects, we can use the |
||
class symbol itself. |
class symbol itself. |
||
< |
<syntaxhighlight lang="picolisp">(class +Singleton) |
||
(dm message1> () |
(dm message1> () |
||
Line 1,819: | Line 1,819: | ||
(dm message2> () |
(dm message2> () |
||
(prinl "This is method 2 on " This) )</ |
(prinl "This is method 2 on " This) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>: (message1> '+Singleton) |
<pre>: (message1> '+Singleton) |
||
Line 1,832: | Line 1,832: | ||
===Native version=== |
===Native version=== |
||
Thread safe version. |
Thread safe version. |
||
< |
<syntaxhighlight lang="purebasic">Global SingletonSemaphore=CreateSemaphore(1) |
||
Interface OO_Interface ; Interface for any value of this type |
Interface OO_Interface ; Interface for any value of this type |
||
Line 1,879: | Line 1,879: | ||
Data.i @OO_Set() |
Data.i @OO_Set() |
||
Data.i @OO_Destroy() |
Data.i @OO_Destroy() |
||
EndDataSection</ |
EndDataSection</syntaxhighlight> |
||
===Simple OOP extension=== |
===Simple OOP extension=== |
||
Using the open-source precompiler [http://www.development-lounge.de/viewtopic.php?t=5915 SimpleOOP]. |
Using the open-source precompiler [http://www.development-lounge.de/viewtopic.php?t=5915 SimpleOOP]. |
||
< |
<syntaxhighlight lang="purebasic">Singleton Class Demo |
||
BeginPrivate |
BeginPrivate |
||
Name$ |
Name$ |
||
Line 1,904: | Line 1,904: | ||
EndMethod |
EndMethod |
||
EndClass</ |
EndClass</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
Line 1,911: | Line 1,911: | ||
Every instance of the Borg class will share the same state: |
Every instance of the Borg class will share the same state: |
||
< |
<syntaxhighlight lang="python">>>> class Borg(object): |
||
__state = {} |
__state = {} |
||
def __init__(self): |
def __init__(self): |
||
Line 1,929: | Line 1,929: | ||
>>> b1.datum is b2.datum |
>>> b1.datum is b2.datum |
||
True |
True |
||
>>> # For any datum!</ |
>>> # For any datum!</syntaxhighlight> |
||
===per MetaClass/AbstractBaseClass=== |
===per MetaClass/AbstractBaseClass=== |
||
Line 1,935: | Line 1,935: | ||
An approximation of the singleton can be made using only class attributes to store data instead of the instance attributes, providing at least one abstract instance method (class can not be instantiated then) and making the rest of the methods being class methods. E.g. |
An approximation of the singleton can be made using only class attributes to store data instead of the instance attributes, providing at least one abstract instance method (class can not be instantiated then) and making the rest of the methods being class methods. E.g. |
||
< |
<syntaxhighlight lang="python"> |
||
import abc |
import abc |
||
Line 1,965: | Line 1,965: | ||
Singleton.printSelf() |
Singleton.printSelf() |
||
print Singleton.state |
print Singleton.state |
||
</syntaxhighlight> |
|||
</lang> |
|||
When executed this code should print out the following:<br> |
When executed this code should print out the following:<br> |
||
<br> |
<br> |
||
Line 1,981: | Line 1,981: | ||
< |
<syntaxhighlight lang="python"> |
||
class Singleton(type): |
class Singleton(type): |
||
_instances = {} |
_instances = {} |
||
Line 1,991: | Line 1,991: | ||
class Logger(object): |
class Logger(object): |
||
__metaclass__ = Singleton |
__metaclass__ = Singleton |
||
</syntaxhighlight> |
|||
</lang> |
|||
or in Python3 |
or in Python3 |
||
< |
<syntaxhighlight lang="python"> |
||
class Logger(metaclass=Singleton): |
class Logger(metaclass=Singleton): |
||
pass |
pass |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
Singletons are not very useful in Racket, because functions that use module state are more straightforward. However, classes are first class values, and therefore they follow the same rules as all other bindings. For example, a class can be made and instantiated but not provided to client files: |
Singletons are not very useful in Racket, because functions that use module state are more straightforward. However, classes are first class values, and therefore they follow the same rules as all other bindings. For example, a class can be made and instantiated but not provided to client files: |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(provide instance) |
(provide instance) |
||
Line 2,011: | Line 2,011: | ||
(super-new))) |
(super-new))) |
||
(define instance (new singleton%)) |
(define instance (new singleton%)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or better, not name the class at all: |
Or better, not name the class at all: |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(provide instance) |
(provide instance) |
||
Line 2,021: | Line 2,021: | ||
(define/public (foo) 123) |
(define/public (foo) 123) |
||
(super-new)))) |
(super-new)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<syntaxhighlight lang="raku" line>class Singleton { |
||
# We create a lexical variable in the class block that holds our single instance. |
# We create a lexical variable in the class block that holds our single instance. |
||
my Singleton $instance = Singleton.bless; # You can add initialization arguments here. |
my Singleton $instance = Singleton.bless; # You can add initialization arguments here. |
||
method new {!!!} # Singleton.new dies. |
method new {!!!} # Singleton.new dies. |
||
method instance { $instance; } |
method instance { $instance; } |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">require 'singleton' |
||
class MySingleton |
class MySingleton |
||
include Singleton |
include Singleton |
||
Line 2,041: | Line 2,041: | ||
a = MySingleton.instance # instance is only created the first time it is requested |
a = MySingleton.instance # instance is only created the first time it is requested |
||
b = MySingleton.instance |
b = MySingleton.instance |
||
puts a.equal?(b) # outputs "true"</ |
puts a.equal?(b) # outputs "true"</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
The '''object''' construct in Scala is a singleton. |
The '''object''' construct in Scala is a singleton. |
||
< |
<syntaxhighlight lang="scala">object Singleton { |
||
// any code here gets executed as if in a constructor |
// any code here gets executed as if in a constructor |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">class Singleton(name) { |
||
static instance; |
static instance; |
||
Line 2,070: | Line 2,070: | ||
s2.name = 'bar'; # change name in s2 |
s2.name = 'bar'; # change name in s2 |
||
say s1.name; #=> 'bar'</ |
say s1.name; #=> 'bar'</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
Clones of Oddball themselves may not be cloned. |
Clones of Oddball themselves may not be cloned. |
||
Methods and slots may still be defined on them: |
Methods and slots may still be defined on them: |
||
< |
<syntaxhighlight lang="slate">define: #Singleton &builder: [Oddball clone]</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk"> |
||
SomeClass class>>sharedInstance |
SomeClass class>>sharedInstance |
||
SharedInstance ifNil: [SharedInstance := self basicNew initialize]. |
SharedInstance ifNil: [SharedInstance := self basicNew initialize]. |
||
^ SharedInstance |
^ SharedInstance |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift"> |
||
class SingletonClass { |
class SingletonClass { |
||
Line 2,099: | Line 2,099: | ||
// Usage |
// Usage |
||
let sharedObject = SingletonClass.sharedInstance |
let sharedObject = SingletonClass.sharedInstance |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Line 2,105: | Line 2,105: | ||
ref http://wiki.tcl.tk/21595 |
ref http://wiki.tcl.tk/21595 |
||
< |
<syntaxhighlight lang="tcl">package require TclOO |
||
# This is a metaclass, a class that defines the behavior of other classes |
# This is a metaclass, a class that defines the behavior of other classes |
||
Line 2,125: | Line 2,125: | ||
return [incr count] |
return [incr count] |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Demonstrating in an interactive shell: |
Demonstrating in an interactive shell: |
||
< |
<syntaxhighlight lang="tcl">% set a [example new] |
||
::oo::Obj20 |
::oo::Obj20 |
||
% set b [example new] ;# note how this returns the same object name |
% set b [example new] ;# note how this returns the same object name |
||
Line 2,140: | Line 2,140: | ||
3 |
3 |
||
% $b counter |
% $b counter |
||
4</ |
4</syntaxhighlight> |
||
=={{header|Tern}}== |
=={{header|Tern}}== |
||
Tern has built-in support for singletons via module declarations. |
Tern has built-in support for singletons via module declarations. |
||
< |
<syntaxhighlight lang="tern">module Singleton { |
||
speak() { |
speak() { |
||
println("I am a singleton"); |
println("I am a singleton"); |
||
Line 2,150: | Line 2,150: | ||
} |
} |
||
Singleton.speak();</ |
Singleton.speak();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,158: | Line 2,158: | ||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
< |
<syntaxhighlight lang="vala">public class Singleton : Object { |
||
static Singleton? instance; |
static Singleton? instance; |
||
Line 2,181: | Line 2,181: | ||
print("Equal.\n"); |
print("Equal.\n"); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
Line 2,187: | Line 2,187: | ||
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. |
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="ecmascript">class Singleton { |
||
// Returns the singleton. If it hasn't been created, creates it first. |
// Returns the singleton. If it hasn't been created, creates it first. |
||
static instance { __instance == null ? __instance = Singleton.new_() : __instance } |
static instance { __instance == null ? __instance = Singleton.new_() : __instance } |
||
Line 2,202: | Line 2,202: | ||
var s2 = Singleton.instance |
var s2 = Singleton.instance |
||
System.print("s1 and s2 are same object = %(Object.same(s1, s2))") |
System.print("s1 and s2 are same object = %(Object.same(s1, s2))") |
||
s1.speak() // call instance method</ |
s1.speak() // call instance method</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,213: | Line 2,213: | ||
A class declared static only has one instance, ever. |
A class declared static only has one instance, ever. |
||
However, a class with the same name & structure could be created in another scope. |
However, a class with the same name & structure could be created in another scope. |
||
< |
<syntaxhighlight lang="zkl">class [static] Borg{ var v } |
||
b1 := Borg; b2 := Borg(); |
b1 := Borg; b2 := Borg(); |
||
b1 == b2 //--> True |
b1 == b2 //--> True |
||
b1.v=123; b2.v.println(); //--> 123</ |
b1.v=123; b2.v.println(); //--> 123</syntaxhighlight> |
||
{{omit from|6502 Assembly}} |
{{omit from|6502 Assembly}} |
||
{{omit from|68000 Assembly}} |
{{omit from|68000 Assembly}} |