Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Singleton
note: Object oriented

View file

@ -0,0 +1,5 @@
A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
<br><br>

View file

@ -0,0 +1,20 @@
package
{
public class Singleton
{
private static var instance:Singleton;
// ActionScript does not allow private or protected constructors.
public function Singleton(enforcer:SingletonEnforcer) {
}
public static function getInstance():Singleton {
if (instance == null) instance = new Singleton(new SingletonEnforcer());
return instance;
}
}
}
internal class SingletonEnforcer {}

View file

@ -0,0 +1,10 @@
package Global_Singleton is
procedure Set_Data (Value : Integer);
function Get_Data return Integer;
private
type Instance_Type is record
-- Define instance data elements
Data : Integer := 0;
end record;
Instance : Instance_Type;
end Global_Singleton;

View file

@ -0,0 +1,21 @@
package body Global_Singleton is
--------------
-- Set_Data --
--------------
procedure Set_Data (Value : Integer) is
begin
Instance.Data := Value;
end Set_Data;
--------------
-- Get_Data --
--------------
function Get_Data return Integer is
begin
return Instance.Data;
end Get_Data;
end Global_Singleton;

View file

@ -0,0 +1,11 @@
package Protected_Singleton is
procedure Set_Data (Value : Integer);
function Get_Data return Integer;
private
protected Instance is
procedure Set(Value : Integer);
function Get return Integer;
private
Data : Integer := 0;
end Instance_Type;
end Protected_Singleton;

View file

@ -0,0 +1,47 @@
package body Protected_Singleton is
--------------
-- Set_Data --
--------------
procedure Set_Data (Value : Integer) is
begin
Instance.Set(Value);
end Set_Data;
--------------
-- Get_Data --
--------------
function Get_Data return Integer is
begin
return Instance.Get;
end Get_Data;
--------------
-- Instance --
--------------
protected body Instance is
---------
-- Set --
---------
procedure Set (Value : Integer) is
begin
Data := Value;
end Set;
---------
-- Get --
---------
function Get return Integer is
begin
return Data;
end Get;
end Instance;
end Protected_Singleton;

View file

@ -0,0 +1,28 @@
b1 := borg()
b2 := borg()
msgbox % "b1 is b2? " . (b1 == b2)
b1.datum := 3
msgbox % "b1.datum := 3`n...`nb1 datum: " b1.datum "`nb2 datum: " b2.datum ; is 3 also
msgbox % "b1.datum is b2.datum ? " (b1.datum == b2.datum)
return
borg(){
static borg
If !borg
borg := Object("__Set", "Borg_Set"
, "__Get", "Borg_Get")
return object(1, borg, "base", borg)
}
Borg_Get(brg, name)
{
Return brg[1, name]
}
Borg_Set(brg, name, val)
{
brg[1, name] := val
Return val
}

View file

@ -0,0 +1,99 @@
#include <stdexcept>
template <typename Self>
class singleton
{
protected:
static Self*
sentry;
public:
static Self&
instance()
{
return *sentry;
}
singleton()
{
if(sentry)
throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!");
sentry = (Self*)this;
}
virtual ~singleton()
{
if(sentry == this)
sentry = 0;
}
};
template <typename Self>
Self*
singleton<Self>::sentry = 0;
/*
Example usage:
*/
#include <iostream>
#include <string>
using namespace
std;
class controller : public singleton<controller>
{
public:
controller(string const& name)
: name(name)
{
trace("begin");
}
~controller()
{
trace("end");
}
void
work()
{
trace("doing stuff");
}
void
trace(string const& message)
{
cout << name << ": " << message << endl;
}
string
name;
};
int
main()
{
controller*
first = new controller("first");
controller::instance().work();
delete first;
/*
No problem, our first controller no longer exists...
*/
controller
second("second");
controller::instance().work();
try
{
/*
Never happens...
*/
controller
goner("goner");
controller::instance().work();
}
catch(exception const& error)
{
cout << error.what() << endl;
}
controller::instance().work();
/*
Never happens (and depending on your system this may or may not print a helpful message!)
*/
controller
goner("goner");
controller::instance().work();
}

View file

@ -0,0 +1,16 @@
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;
}
}
}

View file

@ -0,0 +1,18 @@
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;
}
}
}

View file

@ -0,0 +1,6 @@
public sealed class Singleton3 //Lazy: Yes, but not completely ||| Thread-safe: Yes ||| Uses locking: No
{
private static Singleton3 Instance { get; } = new Singleton3();
static Singleton3() { }
}

View file

@ -0,0 +1,11 @@
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();
}
}

View file

@ -0,0 +1,6 @@
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;
}

View file

@ -0,0 +1,7 @@
#ifndef SILLY_H
#define SILLY_H
extern void JumpOverTheDog( int numberOfTimes);
extern int PlayFetchWithDog( float weightOfStick);
#endif

View file

@ -0,0 +1,25 @@
...
#include "silly.h"
struct sDog {
float max_stick_weight;
int isTired;
int isAnnoyed;
};
static struct sDog lazyDog = { 4.0, 0,0 };
/* define functions used by the functions in header as static */
static int RunToStick( )
{...
}
/* define functions declared in the header file. */
void JumpOverTheDog(int numberOfTimes)
{ ...
lazyDog.isAnnoyed = TRUE;
}
int PlayFetchWithDog( float weightOfStick )
{ ...
if(weightOfStick < lazyDog.max_stick_weight){...
}

View file

@ -0,0 +1,7 @@
...
#include "silly.h"
...
/* code using the dog methods */
JumpOverTheDog( 4);
retrieved = PlayFetchWithDog( 3.1);
...

View file

@ -0,0 +1,24 @@
(defgeneric concat (a b)
(:documentation "Concatenate two phrases."))
(defclass nonempty-phrase ()
((text :initarg :text :reader text)))
(defmethod concat ((a nonempty-phrase) (b nonempty-phrase))
(make-instance 'nonempty-phrase :text (concatenate 'string (text a) " " (text b))))
(defmethod concat ((a (eql 'the-empty-phrase)) b)
b)
(defmethod concat (a (b (eql 'the-empty-phrase)))
a)
(defun example ()
(let ((before (make-instance 'nonempty-phrase :text "Jack"))
(mid (make-instance 'nonempty-phrase :text "went"))
(after (make-instance 'nonempty-phrase :text "to fetch a pail of water")))
(dolist (p (list 'the-empty-phrase
(make-instance 'nonempty-phrase :text "and Jill")))
(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))))))))

View file

@ -0,0 +1,61 @@
module singleton ;
import std.stdio ;
import std.thread ;
import std.random ;
import std.c.time ;
class Dealer {
private static Dealer me ;
static Dealer Instance() {
writefln(" Calling Dealer... ") ;
if(me is null) // Double Checked Lock
synchronized // this part of code can only be executed by one thread a time
if(me is null)
me = new Dealer ;
return me ;
}
private static string[] str = ["(1)Enjoy", "(2)Rosetta", "(3)Code"] ;
private int state ;
private this() {
for(int i = 0 ; i < 3 ; i++) {
writefln("...calling Dealer... ") ;
msleep(rand() & 2047) ;
}
writefln(">>Dealer is called to come in!") ;
state = str.length - 1 ;
}
Dealer nextState() {
synchronized(this) // accessed to Object _this_ is locked ... is it necessary ???
state = (state + 1) % str.length ;
return this ;
}
string toString() { return str[state] ; }
}
class Coder : Thread {
private string name_ ;
Coder hasName(string name) { name_ = name ; return this ; }
override int run() {
msleep(rand() & 1023) ;
writefln(">>%s come in.", name_) ;
Dealer single = Dealer.Instance ;
msleep(rand() & 1023) ;
for(int i = 0 ; i < 3 ; i++) {
writefln("%9s got %-s", name_, single.nextState) ;
msleep(rand() & 1023) ;
}
return 0 ;
}
}
void main() {
Coder x = new Coder ;
Coder y = new Coder ;
Coder z = new Coder ;
x.hasName("Peter").start() ;
y.hasName("Paul").start() ;
z.hasName("Mary").start() ;
x.wait ; y.wait ; z.wait ;
}

View file

@ -0,0 +1,40 @@
unit Singleton;
interface
type
TSingleton = class
private
//Private fields and methods here...
class var _instance: TSingleton;
protected
//Other protected methods here...
public
//Global point of access to the unique instance
class function Create: TSingleton;
destructor Destroy; override;
//Other public methods and properties here...
end;
implementation
{ TSingleton }
class function TSingleton.Create: TSingleton;
begin
if (_instance = nil) then
_instance:= inherited Create as Self;
result:= _instance;
end;
destructor TSingleton.Destroy;
begin
_instance:= nil;
inherited;
end;
end.

View file

@ -0,0 +1,3 @@
def aSingleton {
# ...
}

View file

@ -0,0 +1,17 @@
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

View file

@ -0,0 +1,7 @@
class
SINGLETON
create {SINGLETON_ACCESS}
default_create
feature
-- singleton features go here
end

View file

@ -0,0 +1,10 @@
frozen class
SINGLETON_ACCESS
feature
singleton: SINGLETON
once ("PROCESS")
create Result
ensure
Result /= Void
end
end

View file

@ -0,0 +1,3 @@
s: SINGLETON -- declaration somewhere
s := (create{SINGLETON_ACCESS}).singleton -- in some routine

View file

@ -0,0 +1,4 @@
singleton Singleton
{
// ...
}

View file

@ -0,0 +1,8 @@
class Singleton
{
object theField;
// ...
}
static singleton = new Singleton();

View file

@ -0,0 +1,24 @@
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

View file

@ -0,0 +1,33 @@
-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.

View file

@ -0,0 +1,14 @@
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}

View file

@ -0,0 +1,6 @@
USING: classes.singleton kernel io prettyprint ;
IN: singleton-demo
SINGLETON: bar
GENERIC: foo ( obj -- )
M: bar foo drop "Hello!" print ;

View file

@ -0,0 +1,28 @@
include FMS-SI.f
\ A singleton is created by using normal Forth data
\ allocation words such as value or variable as instance variables.
\ Any number of instances of a singleton class may be
\ instantiated but messages will all operate on the same shared data
\ so it is the same as if only one object has been created.
\ The data name space will remain private to the class.
:class singleton
0 value a
0 value b
:m printa a . ;m
:m printb b . ;m
:m add-a ( n -- ) a + to a ;m
:m add-b ( n -- ) b + to b ;m
;class
singleton s1
singleton s2
singleton s3
4 s1 add-a
9 s2 add-b
s3 printa \ => 4
s3 printb \ => 9
s1 printb \ => 9
s2 printa \ => 4

View file

@ -0,0 +1,49 @@
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

View file

@ -0,0 +1,31 @@
package main
import (
"log"
"math/rand"
"sync"
"time"
)
var (
instance string
once sync.Once // initialize instance with once.Do
)
func claim(color string, w *sync.WaitGroup) {
time.Sleep(time.Duration(rand.Intn(1e8))) // hesitate up to .1 sec
log.Println("trying to claim", color)
once.Do(func() { instance = color })
log.Printf("tried %s. instance: %s", color, instance)
w.Done()
}
func main() {
rand.Seed(time.Now().Unix())
var w sync.WaitGroup
w.Add(2)
go claim("red", &w) // these two attempts run concurrently
go claim("blue", &w)
w.Wait()
log.Println("after trying both, instance =", instance)
}

View file

@ -0,0 +1,14 @@
package singlep
// package level data declarations serve as singleton instance variables
var X, Y int
// package level initialization can serve as constructor code
func init() {
X, Y = 2, 3
}
// package level functions serve as methods for a package-as-a-singleton
func F() int {
return Y - X
}

View file

@ -0,0 +1,12 @@
package main
import (
"fmt"
"singlep"
)
func main() {
// dot selector syntax references package variables and functions
fmt.Println(singlep.X, singlep.Y)
fmt.Println(singlep.F())
}

View file

@ -0,0 +1,24 @@
package single
import (
"log"
"sync"
)
var (
color string
once sync.Once
)
func Color() string {
if color == "" {
panic("color not initialized")
}
return color
}
func SetColor(c string) {
log.Println("color initialization")
once.Do(func() { color = c })
log.Println("color initialized to", color)
}

View file

@ -0,0 +1,12 @@
package red
import (
"log"
"single"
)
func SetColor() {
log.Println("trying to set red")
single.SetColor("red")
}

View file

@ -0,0 +1,12 @@
package blue
import (
"log"
"single"
)
func SetColor() {
log.Println("trying to set blue")
single.SetColor("blue")
}

View file

@ -0,0 +1,24 @@
package main
import (
"log"
"math/rand"
"time"
"blue"
"red"
"single"
)
func main() {
rand.Seed(time.Now().Unix())
switch rand.Intn(3) {
case 1:
red.SetColor()
blue.SetColor()
case 2:
blue.SetColor()
red.SetColor()
}
log.Println(single.Color())
}

View file

@ -0,0 +1,11 @@
@Singleton
class SingletonClass {
def invokeMe() {
println 'invoking method of a singleton class'
}
static void main(def args) {
SingletonClass.instance.invokeMe()
}
}

View file

@ -0,0 +1,13 @@
class Singleton
method print()
write("Hi there.")
end
initially
write("In constructor!")
Singleton := create |self
end
procedure main()
Singleton().print()
Singleton().print()
end

View file

@ -0,0 +1,2 @@
Singleton := Object clone
Singleton clone = Singleton

View file

@ -0,0 +1,26 @@
class Singleton
{
private static Singleton myInstance;
public static Singleton getInstance()
{
if (myInstance == null)
{
synchronized(Singleton.class)
{
if (myInstance == null)
{
myInstance = new Singleton();
}
}
}
return myInstance;
}
protected Singleton()
{
// Constructor code goes here.
}
// Any other methods
}

View file

@ -0,0 +1,13 @@
public class Singleton {
private Singleton() {
// Constructor code goes here.
}
private static class LazyHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}

View file

@ -0,0 +1,20 @@
class Singleton
{
private static Singleton myInstance;
public static Singleton getInstance()
{
if (myInstance == null)
{
myInstance = new Singleton();
}
return myInstance;
}
protected Singleton()
{
// Constructor code goes here.
}
// Any other methods
}

View file

@ -0,0 +1,20 @@
function Singleton() {
if(Singleton._instance) return Singleton._instance;
this.set("");
Singleton._instance = this;
}
Singleton.prototype.set = function(msg) { this.msg = msg; }
Singleton.prototype.append = function(msg) { this.msg += msg; }
Singleton.prototype.get = function() { return this.msg; }
var a = new Singleton();
var b = new Singleton();
var c = new Singleton();
a.set("Hello");
b.append(" World");
c.append("!!!");
document.write( (new Singleton()).get() );

View file

@ -0,0 +1,6 @@
struct IAmaSingleton end
x = IAmaSingleton()
y = IAmaSingleton()
println("x == y is $(x == y) and x === y is $(x === y).")

View file

@ -0,0 +1,9 @@
// version 1.1.2
object Singleton {
fun speak() = println("I am a singleton")
}
fun main(args: Array<String>) {
Singleton.speak()
}

View file

@ -0,0 +1,17 @@
// Define the thread if it doesn't exist
// New definition supersede any current threads.
not ::serverwide_singleton->istype
? define serverwide_singleton => thread {
data public switch = 'x'
}
local(
a = serverwide_singleton,
b = serverwide_singleton,
)
#a->switch = 'a'
#b->switch = 'b'
#a->switch // b

View file

@ -0,0 +1,16 @@
// Define thread level singleton
define singleton => type {
data public switch = 'x'
public oncreate => var(.type)->isa(.type) ? var(.type) | var(.type) := self
}
local(
a = singleton,
b = singleton,
)
#a->switch = 'a'
#b->switch = 'b'
#a->switch // b

View file

@ -0,0 +1,13 @@
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

View file

@ -0,0 +1,22 @@
-- parent script "SingletonDemo"
property _instance
property _someProperty
----------------------------------------
-- @constructor
----------------------------------------
on new (me)
if not voidP(me.script._instance) then return me.script._instance
me.script._instance = me
me._someProperty = 0
return me
end
----------------------------------------
-- sample method
----------------------------------------
on someMethod (me, x)
me._someProperty = me._someProperty + x
return me._someProperty
end

View file

@ -0,0 +1,16 @@
:- object(singleton).
:- public(value/1).
value(Value) :-
state(Value).
:- public(set_value/1).
set_value(Value) :-
retract(state(_)),
assertz(state(Value)).
:- private(state/1).
:- dynamic(state/1).
state(0).
:- end_object.

View file

@ -0,0 +1,7 @@
| ?- singleton::value(Value).
Value = 0
yes
| ?- singleton::(set_value(1), value(Value)).
Value = 1
yes

View file

@ -0,0 +1,54 @@
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

View file

@ -0,0 +1,97 @@
/* NetRexx */
options replace format comments java crossref symbols binary
import java.util.random
class RCSingleton public
method main(args = String[]) public static
RCSingleton.Testcase.main(args)
return
-- ---------------------------------------------------------------------------
class RCSingleton.Instance public
properties private static
_instance = Instance()
properties private
_refCount = int
_random = Random
method Instance() private
this._refCount = 0
this._random = Random()
return
method getInstance public static returns RCSingleton.Instance
return _instance
method getRandom public returns Random
return _random
method addRef public protect
_refCount = _refCount + 1
return
method release public protect
if _refCount > 0 then
_refCount = _refCount - 1
return
method getRefCount public protect returns int
return _refCount
-- ---------------------------------------------------------------------------
class RCSingleton.Testcase public implements Runnable
properties private
_instance = RCSingleton.Instance
method run public
say threadInfo'|-'
thud = Thread.currentThread
_instance = RCSingleton.Instance.getInstance
thud.yield
_instance.addRef
say threadInfo'|'_instance.getRefCount
thud.yield
do
thud.sleep(_instance.getRandom.nextInt(1000))
catch ex = InterruptedException
ex.printStackTrace
end
_instance.release
say threadInfo'|'_instance.getRefCount
return
method main(args = String[]) public static
threads = [ Thread -
Thread(Testcase()), Thread(Testcase()), Thread(Testcase()), -
Thread(Testcase()), Thread(Testcase()), Thread(Testcase()) ]
say threadInfo'|-'
mn = Testcase()
mn._instance = RCSingleton.Instance.getInstance
say mn.threadInfo'|'mn._instance.getRefCount
mn._instance.addRef
say mn.threadInfo'|'mn._instance.getRefCount
do
loop tr over threads
(Thread tr).start
end tr
Thread.sleep(400)
catch ex = InterruptedException
ex.printStackTrace
end
mn._instance.release
say mn.threadInfo'|'mn._instance.getRefCount
return
method threadInfo public static returns String
trd = Thread.currentThread
tid = trd.getId
hc = trd.hashCode
info = Rexx(trd.getName).left(16, '_')':' -
|| Rexx(Long.toString(tid)).right(10, 0)':' -
|| '@'Rexx(Integer.toHexString(hc)).right(8, 0)
return info

View file

@ -0,0 +1,4 @@
type Singleton = object # Singleton* would export
foo*: int
var single* = Singleton(foo: 0)

View file

@ -0,0 +1,4 @@
import singleton
single.foo = 12
echo single.foo

View file

@ -0,0 +1,18 @@
class Singleton {
@singleton : static : Singleton;
New : private () {
}
function : GetInstance() ~ Singleton {
if(@singleton <> Nil) {
@singleton := Singleton->New();
};
return @singleton;
}
method : public : DoStuff() ~ Nil {
...
}
}

View file

@ -0,0 +1,9 @@
// SomeSingleton.h
@interface SomeSingleton : NSObject
{
// any instance variables
}
+ (SomeSingleton *)sharedInstance;
@end

View file

@ -0,0 +1,38 @@
// SomeSingleton.m
@implementation SomeSingleton
+ (SomeSingleton *) sharedInstance
{
static SomeSingleton *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;
}
- (oneway void)release
{
// prevent release
}
- (id)autorelease
{
return self;
}
@end

View file

@ -0,0 +1,10 @@
+ (SomeSingleton *) sharedInstance
{
static SomeSingleton *sharedInstance = nil;
@synchronized(self) {
if (!sharedInstance) {
sharedInstance = [[SomeSingleton alloc] init];
}
}
return sharedInstance;
}

View file

@ -0,0 +1,9 @@
+ (SomeSingleton *) sharedInstance
{
static SomeSingleton *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[SomeSingleton alloc] init];
});
return sharedInstance;
}

View file

@ -0,0 +1,6 @@
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 ;

View file

@ -0,0 +1,6 @@
import: parallel
: testSequence
| s i |
Sequence new(0) ->s
100 loop: i [ #[ s nextValue println ] & ] ;

View file

@ -0,0 +1,32 @@
a = .singleton~new
b = .singleton~new
a~foo = "Rick"
if a~foo \== b~foo then say "A and B are not the same object"
::class singleton
-- initialization method for the class
::method init class
expose singleton
-- mark this as unallocated. We could also just allocate
-- the singleton now, but better practice is probably wait
-- until it is requested
singleton = .nil
-- override the new method. Since this is a guarded
-- method by default, this is thread safe
::method new class
expose singleton
-- first request? Do the real creation now
if singleton == .nil then do
-- forward to the super class. We use this form of
-- FORWARD rather than explicit call ~new:super because
-- this takes care of any arguments passed to NEW as well.
forward class(super) continue
singleton = result
end
return singleton
-- an attribute that can be used to demonstrate this really is
a singleton.
::attribute foo

View file

@ -0,0 +1,11 @@
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

View file

@ -0,0 +1,19 @@
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

View file

@ -0,0 +1,21 @@
class Singleton {
protected static $instance = null;
public $test_var;
private function __construct(){
//Any constructor code
}
public static function getInstance(){
if (is_null(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}
}
$foo = Singleton::getInstance();
$foo->test_var = 'One';
$bar = Singleton::getInstance();
echo $bar->test_var; //Prints 'One'
$fail = new Singleton(); //Fatal error

View file

@ -0,0 +1,29 @@
package Singleton;
use strict;
use warnings;
my $Instance;
sub new {
my $class = shift;
$Instance ||= bless {}, $class; # initialised once only
}
sub name {
my $self = shift;
$self->{name};
}
sub set_name {
my ($self, $name) = @_;
$self->{name} = $name;
}
package main;
my $s1 = Singleton->new;
$s1->set_name('Bob');
printf "name: %s, ref: %s\n", $s1->name, $s1;
my $s2 = Singleton->new;
printf "name: %s, ref: %s\n", $s2->name, $s2;

View file

@ -0,0 +1,19 @@
-- <separate include file>
object chk = NULL
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

View file

@ -0,0 +1,6 @@
global function get_singleton()
if chk==NULL then
chk = new("singleton")
end if
return chk
end function

View file

@ -0,0 +1,7 @@
(class +Singleton)
(dm message1> ()
(prinl "This is method 1 on " This) )
(dm message2> ()
(prinl "This is method 2 on " This) )

View file

@ -0,0 +1,48 @@
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

View file

@ -0,0 +1,23 @@
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

View file

@ -0,0 +1,19 @@
>>> class Borg(object):
__state = {}
def __init__(self):
self.__dict__ = self.__state
# Any other class names/methods
>>> b1 = Borg()
>>> b2 = Borg()
>>> b1 is b2
False
>>> b1.datum = range(5)
>>> b1.datum
[0, 1, 2, 3, 4]
>>> b2.datum
[0, 1, 2, 3, 4]
>>> b1.datum is b2.datum
True
>>> # For any datum!

View file

@ -0,0 +1,29 @@
import abc
class Singleton(object):
"""
Singleton class implementation
"""
__metaclass__ = abc.ABCMeta
state = 1 #class attribute to be used as the singleton's attribute
@abc.abstractmethod
def __init__(self):
pass #this prevents instantiation!
@classmethod
def printSelf(cls):
print cls.state #prints out the value of the singleton's state
#demonstration
if __name__ == "__main__":
try:
a = Singleton() #instantiation will fail!
except TypeError as err:
print err
Singleton.printSelf()
print Singleton.state
Singleton.state = 2
Singleton.printSelf()
print Singleton.state

View file

@ -0,0 +1,9 @@
class Singleton(type):
_instances = {}
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):
__metaclass__ = Singleton

View file

@ -0,0 +1,2 @@
class Logger(metaclass=Singleton):
pass

View file

@ -0,0 +1,6 @@
#lang racket
(provide instance)
(define singleton%
(class object%
(super-new)))
(define instance (new singleton%))

View file

@ -0,0 +1,6 @@
#lang racket
(provide instance)
(define instance
(new (class object%
(define/public (foo) 123)
(super-new))))

View file

@ -0,0 +1,6 @@
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; }
}

View file

@ -0,0 +1,9 @@
require 'singleton'
class MySingleton
include Singleton
# constructor and/or methods go here
end
a = MySingleton.instance # instance is only created the first time it is requested
b = MySingleton.instance
puts a.equal?(b) # outputs "true"

View file

@ -0,0 +1,3 @@
object Singleton {
// any code here gets executed as if in a constructor
}

View file

@ -0,0 +1,21 @@
class Singleton(name) {
static instance;
method new(name) {
instance := Singleton.bless(Hash(:name => name));
}
method new {
Singleton.new(nil);
}
}
var s1 = Singleton('foo');
say s1.name; #=> 'foo'
say s1.object_id; #=> '30424504'
var s2 = Singleton();
say s2.name; #=> 'foo'
say s2.object_id; #=> '30424504'
s2.name = 'bar'; # change name in s2
say s1.name; #=> 'bar'

View file

@ -0,0 +1 @@
define: #Singleton &builder: [Oddball clone]

View file

@ -0,0 +1,4 @@
SomeClass class>>sharedInstance
SharedInstance ifNil: [SharedInstance := self basicNew initialize].
^ SharedInstance

View file

@ -0,0 +1,11 @@
class SingletonClass {
static let sharedInstance = SingletonClass()
///Override the init method and make it private
private override init(){
// User can do additional manipulations here.
}
}
// Usage
let sharedObject = SingletonClass.sharedInstance

View file

@ -0,0 +1,33 @@
;; 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

View file

@ -0,0 +1,21 @@
package require TclOO
# This is a metaclass, a class that defines the behavior of other classes
oo::class create singleton {
superclass oo::class
variable object
unexport create ;# Doesn't make sense to have named singletons
method new args {
if {![info exists object]} {
set object [next {*}$args]
}
return $object
}
}
singleton create example {
method counter {} {
my variable count
return [incr count]
}
}

View file

@ -0,0 +1,14 @@
% set a [example new]
::oo::Obj20
% set b [example new] ;# note how this returns the same object name
::oo::Obj20
% expr {$a == $b}
1
% $a counter
1
% $b counter
2
% $a counter
3
% $b counter
4

View file

@ -0,0 +1,7 @@
module Singleton {
speak() {
println("I am a singleton");
}
}
Singleton.speak();

View file

@ -0,0 +1,24 @@
public class Singleton : Object {
static Singleton? instance;
// Private constructor
Singleton() {
}
// Public constructor
public static Singleton get_instance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
void main() {
Singleton a = Singleton.get_instance();
Singleton b = Singleton.get_instance();
if (a == b) {
print("Equal.\n");
}
}

View file

@ -0,0 +1,16 @@
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

View file

@ -0,0 +1,4 @@
class [static] Borg{ var v }
b1 := Borg; b2 := Borg();
b1 == b2 //--> True
b1.v=123; b2.v.println(); //--> 123