Singleton: Difference between revisions

m
Put languages in alphabetic order
m (add link to Delphi for pascal)
m (Put languages in alphabetic order)
Line 122:
{{works with | AutoHotkey_L}}
Translation of python borg pattern
<lang AutoHotkey>b1 := borg()
b1 := borg()
b2 := borg()
msgbox % "b1 is b2? " . (b1 == b2)
Line 151 ⟶ 150:
Return val
}</lang>
 
=={{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.
Line 197:
 
=={{header|C++}}==
 
===Thread-safe===
'''Operating System:''' Microsoft Windows NT/XP/Vista
:Uses a [[Win32]] flavor [[Mutex#Win32|Mutex]] - a [[POSIX]] flavor [[Mutex#POSIX|Mutex]] could be used.
 
<lang cpp>class Singleton
{
Line 243 ⟶ 241:
===Non-Thread-Safe===
This version doesn't require [[Mutex#C|Mutex]], but it is not safe in a multi-threaded environment.
 
<lang cpp>class Singleton
{
Line 275 ⟶ 272:
A thread safe singleton implementation.
To make it non-thread safe remove lockObject and the lock() statement.
 
<lang csharp>// Usage: Singleton.Instance.SomeMethod()
class Singleton
Line 296 ⟶ 292:
// The rest of the methods
}</lang>
 
=={{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.
 
<lang Erlang>
-module(singleton).
 
-export([get/0, set/1, start/0]).
-export([loop/1]).
% spec singleton:get() -> {ok, Value::any()} | not_set
get() ->
?MODULE ! {get, self()},
receive
{ok, not_set} -> not_set;
Answer -> Answer
end.
% spec singleton:set(Value::any()) -> ok
set(Value) ->
?MODULE ! {set, self(), Value},
receive
ok -> ok
end.
 
start() ->
register(?MODULE, spawn(?MODULE, loop, [not_set])).
 
loop(Value) ->
receive
{get, From} ->
From ! {ok, Value},
loop(Value);
{set, From, NewValue} ->
From ! ok,
loop(NewValue)
end.
</lang>
 
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).
 
<lang Erlang>
1> singleton:get().
not_set
2> singleton:set(apple).
ok
3> singleton:get().
{ok,apple}
4> singleton:set("Pear").
ok
5> singleton:get().
{ok,"Pear"}
6> singleton:set(42).
ok
7> singleton:get().
{ok,42}
</lang>
 
=={{header|Common Lisp}}==
 
Since Common Lisp uses ''generic functions'' for dispatch, creating a class is not necessary. If the superclasses of the singleton are not important, the simplest thing to do is to use a particular symbol; methods use ''eql specializers'' to be applicable to only that object.
 
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.
 
<lang lisp>(defgeneric concat (a b)
(:documentation "Concatenate two phrases."))
Line 385 ⟶ 321:
(make-instance 'nonempty-phrase :text "up the hill")))
(write-line (text (reduce #'concat (list before p mid q after))))))))</lang>
 
Thread safety is irrelevant since the singleton is created at load time, not first access.
 
Line 471 ⟶ 406:
Peter got (3)Code</pre>
 
=={{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.)
<lang Delphi>unit Singleton;
unit Singleton;
 
interface
Line 516 ⟶ 450:
 
=={{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).
 
<lang e>def aSingleton {
# ...
}</lang>
 
=={{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.
<lang Erlang>-module(singleton).
 
-export([get/0, set/1, start/0]).
-export([loop/1]).
% spec singleton:get() -> {ok, Value::any()} | not_set
get() ->
?MODULE ! {get, self()},
receive
{ok, not_set} -> not_set;
Answer -> Answer
end.
% spec singleton:set(Value::any()) -> ok
set(Value) ->
?MODULE ! {set, self(), Value},
receive
ok -> ok
end.
 
start() ->
register(?MODULE, spawn(?MODULE, loop, [not_set])).
 
loop(Value) ->
receive
{get, From} ->
From ! {ok, Value},
loop(Value);
{set, From, NewValue} ->
From ! ok,
loop(NewValue)
end.</lang>
 
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).
 
<lang Erlang>1> singleton:get().
not_set
2> singleton:set(apple).
ok
3> singleton:get().
{ok,apple}
4> singleton:set("Pear").
ok
5> singleton:get().
{ok,"Pear"}
6> singleton:set(42).
ok
7> singleton:get().
{ok,42}</lang>
 
=={{header|Factor}}==
Line 529 ⟶ 514:
SINGLETON: bar
GENERIC: foo ( obj -- )
M: bar foo drop "Hello!" print ;</lang>
</lang>
( scratchpad ) bar foo
Hello!
 
=={{header|Go}}==
While not offering singletons explicity, Go has a couple of ways to do this.
Line 595 ⟶ 580:
SingletonClass.instance.invokeMe()
}
}</lang>
}
</lang>
Output:
<pre>invoking method of a singleton class</pre>
 
==Icon and {{header|Unicon}}==
Icon is not object oriented, but Unicon supports O-O programming.
Line 624 ⟶ 609:
 
=={{header|Io}}==
 
Io does not have globals. But it is easy to make singleton objects:
<lang io>Singleton := Object clone
Line 630 ⟶ 614:
 
=={{header|J}}==
 
In J, all classes are singletons though their objects are not. (Class names may be used in any context where object references may be used, and object references can be used in almost every context where a class name may be used.)
 
Line 636 ⟶ 619:
 
=={{header|Java}}==
 
===Thread-safe===
Double-checked locking; only use with Java 1.5+
only use with Java 1.5+
<lang java>class Singleton
{
Line 662 ⟶ 643:
 
===Non-Thread-Safe===
 
<lang java>class Singleton
{
Line 681 ⟶ 661:
// Any other methods
}</lang>
 
 
=={{header|JavaScript}}==
<lang JavaScript>function Singleton() {
function Singleton() {
if(Singleton._instance) return Singleton._instance;
this.set("");
Line 704 ⟶ 682:
c.append("!!!");
 
document.write( (new Singleton()).get() );</lang>
</lang>
 
=={{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.
<lang logtalk>:- object(singleton).
:- object(singleton).
 
:- public(value/1).
Line 725 ⟶ 701:
state(0).
 
:- end_object.</lang>
</lang>
A simple usage example after compiling and loading the code above:
<lang logtalk>| ?- singleton::value(Value).
| ?- singleton::value(Value).
Value = 0
yes
Line 735 ⟶ 709:
| ?- singleton::(set_value(1), value(Value)).
Value = 1
yes</lang>
</lang>
 
=={{header|PascalObjeck}}==
<lang objeck>class Singleton {
See [[Singleton#Delphi | Delphi]]
@singleton : static : Singleton;
 
New : private () {
=={{header|Perl}}==
}
 
function : GetInstance() ~ Singleton {
if(@singleton <> Nil) {
@singleton := Singleton->New();
};
 
return @singleton;
}
 
method : public : DoStuff() ~ Nil {
...
}
}</lang>
 
=={{header|Objective-C}}==
===Non-Thread-Safe===
(Using Cocoa/OpenStep's NSObject as a base class)
<lang objc>// SomeSingleton.h
@interface SomeSingleton : NSObject
{
// any instance variables
}
 
+ (SomeSingleton*)sharedInstance;
 
@end</lang>
 
<lang objc>// SomeSingleton.m
@implementation SomeSingleton
 
+ (SomeSingleton*) sharedInstance
{
static sharedInstance = nil;
if(!sharedInstance) {
sharedInstance = [[SomeSingleton alloc] init];
}
return sharedInstance;
}
 
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
 
- (id)retain
{
return self;
}
 
- (unsigned)retainCount
{
return UINT_MAX;
}
 
- (void)release
{
// prevent release
}
 
- (id)autorelease
{
return self;
}
 
@end</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.
<lang oz>declare
local
class Singleton
meth init
skip
end
end
L = {NewLock}
Instance
in
fun {GetInstance}
lock L then
if {IsFree Instance} then
Instance = {New Singleton init}
end
Instance
end
end
end</lang>
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".
 
<lang =={{header|Perl>}}==
<lang Perl>package Singleton;
use strict;
use warnings;
Line 772 ⟶ 835:
 
my $s2 = Singleton->new;
printf "name: %s, ref: %s\n", $s2->name, $s2;</lang>
</lang>
 
=={{header|Perl 6}}==
 
<lang Perl6>class Singleton {
# We create a lexical variable in the class block that holds our single instance.
Line 850 ⟶ 911:
>>> # For any datum!</lang>
 
=={{header|Objeck}}==
<lang objeck>
class Singleton {
@singleton : static : Singleton;
 
New : private () {
}
 
function : GetInstance() ~ Singleton {
if(@singleton <> Nil) {
@singleton := Singleton->New();
};
 
return @singleton;
}
 
method : public : DoStuff() ~ Nil {
...
}
}
</lang>
 
=={{header|Objective-C}}==
===Non-Thread-Safe===
 
(Using Cocoa/OpenStep's NSObject as a base class)
<lang objc>// SomeSingleton.h
@interface SomeSingleton : NSObject
{
// any instance variables
}
 
+ (SomeSingleton*)sharedInstance;
 
@end</lang>
 
<lang objc>// SomeSingleton.m
@implementation SomeSingleton
 
+ (SomeSingleton*) sharedInstance
{
static sharedInstance = nil;
if(!sharedInstance) {
sharedInstance = [[SomeSingleton alloc] init];
}
return sharedInstance;
}
 
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
 
- (id)retain
{
return self;
}
 
- (unsigned)retainCount
{
return UINT_MAX;
}
 
- (void)release
{
// prevent release
}
 
- (id)autorelease
{
return self;
}
 
@end</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.
<lang oz>declare
local
class Singleton
meth init
skip
end
end
L = {NewLock}
Instance
in
fun {GetInstance}
lock L then
if {IsFree Instance} then
Instance = {New Singleton init}
end
Instance
end
end
end</lang>
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|PureBasic}}==
===Native version===
Line 1,025 ⟶ 989:
 
=={{header|Ruby}}==
 
<lang ruby>require 'singleton'
class MySingleton
Line 1,037 ⟶ 1,000:
 
=={{header|Scala}}==
 
The '''object''' construct in Scala is a singleton.
 
<lang scala>object Singleton {
// any code here gets executed as if in a constructor
Anonymous user