Singleton: Difference between revisions

14,414 bytes added ,  23 days ago
Add Ecstasy example
(Tern Programming Language)
(Add Ecstasy example)
 
(24 intermediate revisions by 17 users not shown)
Line 6:
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">package
{
public class Singleton
Line 25:
}
 
internal class SingletonEnforcer {}</langsyntaxhighlight>
 
=={{header|Ada}}==
===Non Thread Safe===
<langsyntaxhighlight lang="ada">package Global_Singleton is
procedure Set_Data (Value : Integer);
function Get_Data return Integer;
Line 38:
end record;
Instance : Instance_Type;
end Global_Singleton;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ada">package body Global_Singleton is
 
--------------
Line 60:
end Get_Data;
 
end Global_Singleton;</langsyntaxhighlight>
 
===Thread Safe===
<langsyntaxhighlight lang="ada">package Protected_Singleton is
procedure Set_Data (Value : Integer);
function Get_Data return Integer;
Line 73:
Data : Integer := 0;
end Instance_Type;
end Protected_Singleton;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ada">package body Protected_Singleton is
 
--------------
Line 121:
end Instance;
 
end Protected_Singleton;</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
{{works with | AutoHotkey_L}}
Translation of python borg pattern
<langsyntaxhighlight AutoHotkeylang="autohotkey">b1 := borg()
b2 := borg()
msgbox % "b1 is b2? " . (b1 == b2)
Line 153:
brg[1, name] := val
Return val
}</langsyntaxhighlight>
 
=={{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}}==
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.
<langsyntaxhighlight lang="c">#ifndef SILLY_H
#define SILLY_H
 
Line 163 ⟶ 315:
extern int PlayFetchWithDog( float weightOfStick);
 
#endif</langsyntaxhighlight>
Then in a separate C source (.c) file, define your structures, variables and functions.
<langsyntaxhighlight lang="c">...
#include "silly.h"
 
Line 189 ⟶ 341:
{ ...
if(weightOfStick < lazyDog.max_stick_weight){...
}</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="c">...
#include "silly.h"
...
Line 198 ⟶ 350:
JumpOverTheDog( 4);
retrieved = PlayFetchWithDog( 3.1);
...</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
===First attempt at thread-safety using locking.===
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).
<syntaxhighlight lang="csharp">public sealed class Singleton1 //Lazy: Yes ||| Thread-safe: Yes ||| Uses locking: Yes
{
private static Singleton1 instance;
private static readonly object lockObj = new object();
public static Singleton1 Instance {
get {
lock(lockObj) {
if (instance == null) {
instance = new Singleton1();
}
}
return instance;
}
}
}</syntaxhighlight>
 
===Fixes excessive locking by double-checking for null.===
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 readonly object lockObj = new object();
 
public static Singleton2 Instance {
get {
if (instance == null) {
lock(lockObj) {
if (instance == null) {
instance = new Singleton2();
}
}
}
return instance;
}
}
}</syntaxhighlight>
 
===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.
<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();
static Singleton3() { }
}</syntaxhighlight>
 
===Truly lazy by using an inner class.===
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;
private class SingletonHolder
{
static SingletonHolder() { }
internal static readonly Singleton4 instance = new Singleton4();
}
}</syntaxhighlight>
 
===Using Lazy<T>===
C# has a dedicated type for lazy initialization: Lazy<T>.<br />
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());
public static Singleton5 Instance => lazy.Value;
}</syntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="cpp">
#include <stdexcept>
 
Line 303 ⟶ 530:
controller::instance().work();
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
===First attempt at thread-safety using locking.===
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).
<lang csharp>public sealed class Singleton1 //Lazy: Yes ||| Thread-safe: Yes ||| Uses locking: Yes
{
private static Singleton1 instance;
private static readonly object lockObj = new object();
public static Singleton1 Instance {
get {
lock(lockObj) {
if (instance == null) {
instance = new Singleton1();
}
}
return instance;
}
}
}</lang>
 
===Fixes excessive locking by double-checking for null.===
Still uses locking and implementation is ugly and verbose.
<lang csharp>public sealed class Singleton2 //Lazy: Yes ||| Thread-safe: Yes ||| Uses locking: Yes, but only once
{
private static Singleton2 instance;
private static readonly object lockObj = new object();
 
public static Singleton2 Instance {
get {
if (instance == null) {
lock(lockObj) {
if (instance == null) {
instance = new Singleton2();
}
}
}
return instance;
}
}
}</lang>
 
===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.
<lang csharp>public sealed class Singleton3 //Lazy: Yes, but not completely ||| Thread-safe: Yes ||| Uses locking: No
{
private static Singleton3 Instance { get; } = new Singleton3();
static Singleton3() { }
}</lang>
 
===Truly lazy by using an inner class.===
This version is completely lazy but the code looks more complicated than it needs to be.
<lang csharp>public sealed class Singleton4 //Lazy: Yes ||| Thread-safe: Yes ||| Uses locking: No
{
public static Singleton4 Instance => SingletonHolder.instance;
private class SingletonHolder
{
static SingletonHolder() { }
internal static readonly Singleton4 instance = new Singleton4();
}
}</lang>
 
===Using Lazy<T>===
C# has a dedicated type for lazy initialization: Lazy<T>.<br />
It makes implementing a Singleton really easy. Recommended.
<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());
public static Singleton5 Instance => lazy.Value;
}</lang>
 
=={{header|Caché ObjectScript}}==
Line 384 ⟶ 536:
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.
 
<langsyntaxhighlight lang="cos">
/// 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
Line 516 ⟶ 668:
 
}
</syntaxhighlight>
</lang>
 
{{out|Examples}}
Line 530 ⟶ 682:
 
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.
<langsyntaxhighlight lang="lisp">(defgeneric concat (a b)
(:documentation "Concatenate two phrases."))
 
Line 553 ⟶ 705:
(dolist (q (list 'the-empty-phrase
(make-instance 'nonempty-phrase :text "up the hill")))
(write-line (text (reduce #'concat (list before p mid q after))))))))</langsyntaxhighlight>
Thread safety is irrelevant since the singleton is created at load time, not first access.
 
=={{header|D}}==
<langsyntaxhighlight lang="d">module singleton ;
import std.stdio ;
import std.thread ;
Line 617 ⟶ 769:
 
x.wait ; y.wait ; z.wait ;
}</langsyntaxhighlight>
{{out}}
<pre>>>Mary come in.
Line 641 ⟶ 793:
=={{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.)
<langsyntaxhighlight Delphilang="delphi">unit Singleton;
 
interface
Line 680 ⟶ 832:
end;
 
end.</langsyntaxhighlight>
 
=={{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).
<langsyntaxhighlight lang="e">def aSingleton {
# ...
}</langsyntaxhighlight>
 
=={{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 693 ⟶ 878:
 
'''Implementation:'''
<langsyntaxhighlight Eiffellang="eiffel">class
SINGLETON
create {SINGLETON_ACCESS}
Line 699 ⟶ 884:
feature
-- singleton features go here
end</langsyntaxhighlight>
<langsyntaxhighlight Eiffellang="eiffel">frozen class
SINGLETON_ACCESS
feature
Line 709 ⟶ 894:
Result /= Void
end
end</langsyntaxhighlight>
'''Usage:'''
<langsyntaxhighlight Eiffellang="eiffel">s: SINGLETON -- declaration somewhere
 
s := (create{SINGLETON_ACCESS}).singleton -- in some routine</syntaxhighlight>
 
s := (create{SINGLETON_ACCESS}).singleton -- in some routine</lang>
=={{header|Elena}}==
Stateless singleton
<langsyntaxhighlight lang="elena">
singleton Singleton
{
// ...
}
</syntaxhighlight>
</lang>
Normal singleton
<langsyntaxhighlight lang="elena">class Singleton
{
object theField;
Line 730 ⟶ 916:
}
 
static singleton = new Singleton();</langsyntaxhighlight>
 
=={{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}}==
<syntaxhighlight lang="epoxy">fn Singleton()
if this.self then return this.self cls
var new: {}
iter k,v as this._props do
new[k]:v
cls
this.self:new
return new
cls
Singleton._props: {
name: "Singleton",
fn setName(self,new)
self.name:new
cls,
}
 
var MySingleton: Singleton()
log(MySingleton == Singleton()) --true
log(MySingleton.name) --Singleton
 
var NewSingleton: Singleton()
NewSingleton>>setName("Test")
 
log(MySingleton.name) --Test</syntaxhighlight>
{{out}}
<pre>
true
Singleton
Test
</pre>
 
=={{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.
<langsyntaxhighlight Erlanglang="erlang">-module(singleton).
 
-export([get/0, set/1, start/0]).
Line 766 ⟶ 1,010:
From ! ok,
loop(NewValue)
end.</langsyntaxhighlight>
 
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).
 
<langsyntaxhighlight Erlanglang="erlang">1> singleton:get().
not_set
2> singleton:set(apple).
Line 783 ⟶ 1,027:
ok
7> singleton:get().
{ok,42}</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: classes.singleton kernel io prettyprint ;
IN: singleton-demo
 
SINGLETON: bar
GENERIC: foo ( obj -- )
M: bar foo drop "Hello!" print ;</langsyntaxhighlight>
( scratchpad ) bar foo
Hello!
Line 799 ⟶ 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
<langsyntaxhighlight lang="forth">include FMS-SIFMS2VT.f
\ A singleton is created by using normal Forth data
Line 829 ⟶ 1,073:
s1 printb \ => 9
s2 printa \ => 4
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
Line 835 ⟶ 1,079:
 
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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 865 ⟶ 1,109:
w.Wait()
log.Println("after trying both, instance =", instance)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 880 ⟶ 1,124:
 
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.
<langsyntaxhighlight lang="go">package singlep
 
// package level data declarations serve as singleton instance variables
Line 893 ⟶ 1,137:
func F() int {
return Y - X
}</langsyntaxhighlight>
Example program using the package:
<langsyntaxhighlight lang="go">package main
 
import (
Line 906 ⟶ 1,150:
fmt.Println(singlep.X, singlep.Y)
fmt.Println(singlep.F())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 917 ⟶ 1,161:
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.
 
<langsyntaxhighlight lang="go">package single
 
import (
Line 940 ⟶ 1,184:
once.Do(func() { color = c })
log.Println("color initialized to", color)
}</langsyntaxhighlight>
<langsyntaxhighlight lang="go">package red
 
import (
Line 952 ⟶ 1,196:
log.Println("trying to set red")
single.SetColor("red")
}</langsyntaxhighlight>
<langsyntaxhighlight lang="go">package blue
 
import (
Line 964 ⟶ 1,208:
log.Println("trying to set blue")
single.SetColor("blue")
}</langsyntaxhighlight>
<langsyntaxhighlight lang="go">package main
 
import (
Line 988 ⟶ 1,232:
}
log.Println(single.Color())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,001 ⟶ 1,245:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">@Singleton
class SingletonClass {
 
Line 1,011 ⟶ 1,255:
SingletonClass.instance.invokeMe()
}
}</langsyntaxhighlight>
{{out}}
<pre>invoking method of a singleton class</pre>
Line 1,017 ⟶ 1,261:
==Icon and {{header|Unicon}}==
Icon is not object oriented, but Unicon supports O-O programming.
<langsyntaxhighlight lang="unicon">class Singleton
method print()
write("Hi there.")
Line 1,029 ⟶ 1,273:
Singleton().print()
Singleton().print()
end</langsyntaxhighlight>
 
This Unicon example uses a number of Icon features.
Line 1,041 ⟶ 1,285:
=={{header|Io}}==
Io does not have globals. But it is easy to make singleton objects:
<langsyntaxhighlight lang="io">Singleton := Object clone
Singleton clone = Singleton</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,052 ⟶ 1,296:
===Thread-safe===
[[wp:Double-checked locking]]; only use with Java 1.5+
<langsyntaxhighlight lang="java">class Singleton
{
private static Singleton myInstance;
Line 1,077 ⟶ 1,321:
 
// Any other methods
}</langsyntaxhighlight>
 
===Thread-Safe Lazy-Loaded===
This is the [[wp:Initialization-on-demand holder idiom]].
<langsyntaxhighlight lang="java">public class Singleton {
private Singleton() {
// Constructor code goes here.
Line 1,093 ⟶ 1,337:
return LazyHolder.INSTANCE;
}
}</langsyntaxhighlight>
 
===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>
 
===Non-Thread-Safe===
<langsyntaxhighlight lang="java">class Singleton
{
private static Singleton myInstance;
Line 1,115 ⟶ 1,377:
 
// Any other methods
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">function Singleton() {
if(Singleton._instance) return Singleton._instance;
this.set("");
Line 1,137 ⟶ 1,399:
c.append("!!!");
 
document.write( (new Singleton()).get() );</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="julia">
typestruct IAmaSingleton end
 
x = IAmaSingleton()
Line 1,148 ⟶ 1,410:
 
println("x == y is $(x == y) and x === y is $(x === y).")
</syntaxhighlight>
</lang>
 
=={{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:
<langsyntaxhighlight lang="scala">// version 1.1.2
 
object Singleton {
Line 1,160 ⟶ 1,422:
fun main(args: Array<String>) {
Singleton.speak()
}</langsyntaxhighlight>
 
{{out}}
Line 1,166 ⟶ 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,173 ⟶ 1,494:
===Server wide singleton===
 
<langsyntaxhighlight Lassolang="lasso">// Define the thread if it doesn't exist
// New definition supersede any current threads.
Line 1,189 ⟶ 1,510:
#b->switch = 'b'
 
#a->switch // b</langsyntaxhighlight>
 
===Thread level singleton===
 
<langsyntaxhighlight Lassolang="lasso">// Define thread level singleton
 
define singleton => type {
Line 1,208 ⟶ 1,529:
#b->switch = 'b'
 
#a->switch // b</langsyntaxhighlight>
 
=={{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.
<syntaxhighlight lang="latitude">Singleton ::= Object clone tap {
self id := 0.
self newID := {
self id := self id + 1.
}.
self clone := {
err ArgError clone tap { self message := "Singleton object!". } throw.
}.
}.
 
println: Singleton newID. ; 1
println: Singleton newID. ; 2
println: Singleton newID. ; 3</syntaxhighlight>
 
=={{header|Lingo}}==
In Lingo a Singleton class can be implemented like this:
<langsyntaxhighlight lang="lingo">-- parent script "SingletonDemo"
 
property _instance
Line 1,233 ⟶ 1,570:
me._someProperty = me._someProperty + x
return me._someProperty
end</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="logtalk">:- object(singleton).
 
:- public(value/1).
Line 1,252 ⟶ 1,589:
state(0).
 
:- end_object.</langsyntaxhighlight>
A simple usage example after compiling and loading the code above:
<langsyntaxhighlight lang="logtalk">| ?- singleton::value(Value).
Value = 0
yes
Line 1,260 ⟶ 1,597:
| ?- singleton::(set_value(1), value(Value)).
Value = 1
yes</langsyntaxhighlight>
 
=={{header|NetRexx}}==
Uses a static field to avoid synchronization problems and the ''flawed'' &quot;double-checked locking&quot; 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.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 1,362 ⟶ 1,699:
return info
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,392 ⟶ 1,729:
=={{header|Nim}}==
In the file <code>singleton.nim</code> we don't export the type, so new objects can't be created:
<langsyntaxhighlight lang="nim">type Singleton = object # Singleton* would export
foo*: int
 
var single* = Singleton(foo: 0)</langsyntaxhighlight>
Then in another file we can use the singleton object:
<langsyntaxhighlight lang="nim">import singleton
 
single.foo = 12
echo single.foo</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class Singleton {
@singleton : static : Singleton;
 
Line 1,420 ⟶ 1,757:
...
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
===Non-Thread-Safe===
(Using Cocoa/OpenStep's NSObject as a base class)
<langsyntaxhighlight lang="objc">// SomeSingleton.h
@interface SomeSingleton : NSObject
{
Line 1,433 ⟶ 1,770:
+ (SomeSingleton *)sharedInstance;
 
@end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="objc">// SomeSingleton.m
@implementation SomeSingleton
 
Line 1,472 ⟶ 1,809:
}
 
@end</langsyntaxhighlight>
 
===Thread-Safe===
Same as above except:
<langsyntaxhighlight lang="objc">+ (SomeSingleton *) sharedInstance
{
static SomeSingleton *sharedInstance = nil;
Line 1,485 ⟶ 1,822:
}
return sharedInstance;
}</langsyntaxhighlight>
 
===With GCD===
Same as above except:
<langsyntaxhighlight lang="objc">+ (SomeSingleton *) sharedInstance
{
static SomeSingleton *sharedInstance = nil;
Line 1,497 ⟶ 1,834:
});
return sharedInstance;
}</langsyntaxhighlight>
 
===With class methods===
Line 1,503 ⟶ 1,840:
 
In other words, here the class object serves as the singleton object. The "singleton class" is the metaclass of the class. The downside of this approach is that the "singleton class" (the metaclass of the class) cannot be made to explicitly inherit from a class of the user's choice, or implement a protocol of the user's choice. Also, there is no way to prevent subclasses of the class from being made, thus effectively creating "multiple instances" of the singleton class. Also, one cannot declare properties on the singleton (the class object).
 
 
=={{header|Oforth}}==
Line 1,515 ⟶ 1,851:
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.
 
<langsyntaxhighlight Oforthlang="oforth">Object Class new: Sequence(channel)
Sequence method: initialize(initialValue)
Channel newSize(1) := channel
@channel send(initialValue) drop ;
 
Sequence method: nextValue @channel receive dup 1 + @channel send drop ;</langsyntaxhighlight>
 
Usage :
<langsyntaxhighlight Oforthlang="oforth">import: parallel
 
: testSequence
| s i |
Sequence new(0) ->s
100 loop: i [ #[ s nextValue println ] & ] ;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
a = .singleton~new
b = .singleton~new
Line 1,564 ⟶ 1,900:
a singleton.
::attribute foo
</syntaxhighlight>
</lang>
 
=={{header|OxygenBasic}}==
The singleton contains static members only. It may be instantiated any number of times, but the members will all be shared.
<lang oxygenbasic>
class singleton
static sys a,b,c
static string s,t,u
static double x,y,z
end class
 
'TEST
'====
 
singleton A
singleton B
A.c=3
print B.c 'result 3
print sizeof B 'result 0
</lang>
 
=={{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.
<langsyntaxhighlight lang="oz">declare
local
class Singleton
Line 1,605 ⟶ 1,922:
end
end
end</langsyntaxhighlight>
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}}==
<langsyntaxhighlight Perllang="perl">package Singleton;
use strict;
use warnings;
Line 1,637 ⟶ 1,954:
 
my $s2 = Singleton->new;
printf "name: %s, ref: %s\n", $s2->name, $s2;</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
{{libheader|Phix/Class}}
<lang perl6>class Singleton {
Not really any special handling for singletons in Phix, but you can do something like this,
# We create a lexical variable in the class block that holds our single instance.
or keep check() private and invoke it internally from a few critical routines.
my Singleton $instance = Singleton.bless; # You can add initialization arguments here.
Needs 0.8.1+
method new {!!!} # Singleton.new dies.
<syntaxhighlight lang="phix">-- <separate include file>
method instance { $instance; }
object chk = NULL
}</lang>
class singleton
public procedure check()
if chk==NULL then
chk = this
elsif this!=chk then
?9/0
end if
?"ok"
end procedure
end class
 
global singleton s = new()
--global singleton s2 = new()
-- </separate include file>
 
s.check()
--s2.check() -- dies</syntaxhighlight>
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).
The above separate file prohibits the use of (other) <code>singleton s = new()</code> everywhere, however
<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:
<syntaxhighlight lang="phix">global function get_singleton()
if chk==NULL then
chk = new("singleton")
end if
return chk
end function</syntaxhighlight>
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 share the whole delete_routine()'d res, and that would probably be best achieved by setting a new
flag, say S_SINGLETON or S_STATIC, alongside and triggered via similar syntax to S_ABSTRACT/S_NULLABLE.
Maybe.
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">class Singleton {
protected static $instance = null;
public $test_var;
Line 1,668 ⟶ 2,018:
echo $bar->test_var; //Prints 'One'
 
$fail = new Singleton(); //Fatal error</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
As there is no physical difference between classes and objects, we can use the
class symbol itself.
<langsyntaxhighlight PicoLisplang="picolisp">(class +Singleton)
 
(dm message1> ()
Line 1,679 ⟶ 2,029:
 
(dm message2> ()
(prinl "This is method 2 on " This) )</langsyntaxhighlight>
{{out}}
<pre>: (message1> '+Singleton)
Line 1,690 ⟶ 2,040:
 
=={{header|Python}}==
===per Borg Design===
In Python we use the [http://code.activestate.com/recipes/66531/ Borg pattern] to share state between instances rather than concentrate on identity.
 
Every instance of the Borg class will share the same state:
<langsyntaxhighlight lang="python">>>> class Borg(object):
__state = {}
def __init__(self):
Line 1,711 ⟶ 2,062:
>>> b1.datum is b2.datum
True
>>> # For any datum!</langsyntaxhighlight>
 
===per MetaClass/AbstractBaseClass===
 
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.
 
<langsyntaxhighlight lang="python">
import abc
 
Line 1,745 ⟶ 2,098:
Singleton.printSelf()
print Singleton.state
</syntaxhighlight>
</lang>
When executed this code should print out the following:<br>
<br>
Line 1,756 ⟶ 2,109:
So, instantiation is not possible. Only a single object is available, and it behaves as a singleton.
 
=={{header|PureBasic}}==
===Native version===
Thread safe version.
<lang PureBasic>Global SingletonSemaphore=CreateSemaphore(1)
 
Interface OO_Interface ; Interface for any value of this type
Get.i()
Set(Value.i)
Destroy()
EndInterface
 
===per MetaClass===
Structure OO_Structure ; The *VTable structure
Get.i
Set.i
Destroy.i
EndStructure
 
Structure OO_Var
*VirtualTable.OO_Structure
Value.i
EndStructure
 
<syntaxhighlight lang="python">
Procedure OO_Get(*Self.OO_Var)
class Singleton(type):
ProcedureReturn *Self\Value
_instances = {}
EndProcedure
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
 
class Logger(object):
Procedure OO_Set(*Self.OO_Var, n)
__metaclass__ = Singleton
*Self\Value = n
</syntaxhighlight>
EndProcedure
 
or in Python3
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
 
<syntaxhighlight lang="python">
DataSection
class Logger(metaclass=Singleton):
VTable:
pass
Data.i @OO_Get()
</syntaxhighlight>
Data.i @OO_Set()
Data.i @OO_Destroy()
EndDataSection</lang>
===Simple OOP extension===
Using the open-source precompiler [http://www.development-lounge.de/viewtopic.php?t=5915 SimpleOOP].
<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</lang>
 
=={{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:
<langsyntaxhighlight lang="racket">
#lang racket
(provide instance)
Line 1,843 ⟶ 2,144:
(super-new)))
(define instance (new singleton%))
</syntaxhighlight>
</lang>
 
Or better, not name the class at all:
<langsyntaxhighlight lang="racket">
#lang racket
(provide instance)
Line 1,853 ⟶ 2,154:
(define/public (foo) 123)
(super-new))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>class Singleton {
# 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.
method new {!!!} # Singleton.new dies.
method instance { $instance; }
}</syntaxhighlight>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'singleton'
class MySingleton
include Singleton
Line 1,864 ⟶ 2,174:
a = MySingleton.instance # instance is only created the first time it is requested
b = MySingleton.instance
puts a.equal?(b) # outputs "true"</langsyntaxhighlight>
 
=={{header|Scala}}==
The '''object''' construct in Scala is a singleton.
<langsyntaxhighlight lang="scala">object Singleton {
// any code here gets executed as if in a constructor
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class Singleton(name) {
static instance;
 
Line 1,893 ⟶ 2,203:
 
s2.name = 'bar'; # change name in s2
say s1.name; #=> 'bar'</langsyntaxhighlight>
 
=={{header|Slate}}==
Clones of Oddball themselves may not be cloned.
Methods and slots may still be defined on them:
<langsyntaxhighlight lang="slate">define: #Singleton &builder: [Oddball clone]</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">
SomeClass class>>sharedInstance
 
SharedInstance ifNil: [SharedInstance := self basicNew initialize].
^ SharedInstance
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">
 
class SingletonClass {
Line 1,922 ⟶ 2,232:
// Usage
let sharedObject = SingletonClass.sharedInstance
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
Line 1,928 ⟶ 2,238:
 
ref http://wiki.tcl.tk/21595
<langsyntaxhighlight lang="tcl">package require TclOO
 
# This is a metaclass, a class that defines the behavior of other classes
Line 1,948 ⟶ 2,258:
return [incr count]
}
}</langsyntaxhighlight>
Demonstrating in an interactive shell:
<langsyntaxhighlight lang="tcl">% set a [example new]
::oo::Obj20
% set b [example new] ;# note how this returns the same object name
Line 1,963 ⟶ 2,273:
3
% $b counter
4</langsyntaxhighlight>
 
=={{header|Tern}}==
Tern has built-in support for singletons via module declarations.
<langsyntaxhighlight lang="tern">module Singleton {
speak() {
println("I am a singleton");
Line 1,973 ⟶ 2,283:
}
 
Singleton.speak();</langsyntaxhighlight>
 
{{out}}
Line 1,979 ⟶ 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}}==
<langsyntaxhighlight Valalang="vala">public class Singleton : Object {
static Singleton? instance;
 
Line 2,004 ⟶ 2,364:
print("Equal.\n");
}
}</langsyntaxhighlight>
 
=={{header|Wren}}==
Although it's possible to create a singleton in Wren, you have to rely on no one calling the 'private' constructor directly. This is because there is currently no way to create a private method in Wren - all you can do is to suffix the name with an underscore to indicate by convention it's for internal use only.
 
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="wren">class Singleton {
// Returns the singleton. If it hasn't been created, creates it first.
static instance { __instance == null ? __instance = Singleton.new_() : __instance }
 
// Private constructor.
construct new_() {}
 
// instance method
speak() { System.print("I'm a singleton.") }
 
}
 
var s1 = Singleton.instance
var s2 = Singleton.instance
System.print("s1 and s2 are same object = %(Object.same(s1, s2))")
s1.speak() // call instance method</syntaxhighlight>
 
{{out}}
<pre>
s1 and s2 are same object = true
I'm a singleton.
</pre>
 
=={{header|zkl}}==
A class declared static only has one instance, ever.
However, a class with the same name & structure could be created in another scope.
<langsyntaxhighlight lang="zkl">class [static] Borg{ var v }
b1 := Borg; b2 := Borg();
b1 == b2 //--> True
b1.v=123; b2.v.println(); //--> 123</langsyntaxhighlight>
{{omit from|6502 Assembly}}
 
{{omit from|68000 Assembly}}
{{omit from|8086 Assembly}}
{{omit from|ARM Assembly}}
{{omit from|AWK}}
{{omit from|GAP}}
Line 2,022 ⟶ 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}}
{{omit from|Standard ML}}
{{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}}
{{omit from|ZX Spectrum Basic|Does not have user-defined data structures or objects.}}
162

edits