Singleton pattern

「Singleton pattern」 is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects.

Lazy Initialization

1
2
3
4
5
6
7
8
9
10
11
12
13

public final class SingletonDemo {
private static SingletonDemo instance = null;
private SingletonDemo() { }

public static synchronized SingletonDemo getInstance() {
if (instance == null) {
instance = new SingletonDemo();
}

return instance;
}
}

Eager initialization

1
2
3
4
5
6
7
8
9
10

public final class Singleton {
private static final Singleton INSTANCE = new Singleton();

private Singleton() {}

public static Singleton getInstance() {
return INSTANCE;
}
}

This Eager Man may have several advantages:

  • The static initializer is run when the class is initialized, after class loading but before the class is used by any thread.

  • There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required.

  • The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.

Static block initialization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

public final class Singleton {
private static final Singleton instance;

static { // For error checking or ...
try {
instance = new Singleton();
} catch (Exception e) {
throw new RuntimeException("Darn, an error occurred!", e);
}
}

public static Singleton getInstance() {
return instance;
}

private Singleton() {
// ...
}
}

Initialization-on-demand holder idiom

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

public final class Singleton {
// Private constructor. Prevents instantiation from other classes.
private Singleton() { }

/**
* Initializes singleton.
*
* {@link SingletonHolder} is loaded on the first execution of {@link Singleton#getInstance()} or the first access to
* {@link SingletonHolder#INSTANCE}, not before.
*/

private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}

The enum way

1
2
3
4
5
6
7

public enum Singleton {
INSTANCE;
public void execute (String arg) {
// Perform operation here
}
}

Python Examples

__new__

1
2
3
4
5
6
7
8
class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)
return cls._instance

class MyClass(Singleton):
a = 1

Share __dict__

1
2
3
4
5
6
7
8
9
10

class Borg(object):
_state = {}
def __new__(cls, *args, **kw):
ob = super(Borg, cls).__new__(cls, *args, **kw)
ob.__dict__ = cls._state
return ob

class MyClass2(Borg):
a = 1

Class Decorator

1
2
3
4
5
6
7
8
9
10
11
12

def singleton(cls, *args, **kw):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return getinstance

@singleton
class MyClass:
pass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#  Decorator returning a class with the same name

def singleton(class_):
class class_w(class_):
_instance = None
def __new__(class_, *args, **kwargs):
if class_w._instance is None:
class_w._instance = super(class_w,
class_).__new__(class_,
*args,
**kwargs)
class_w._instance._sealed = False
return class_w._instance
def __init__(self, *args, **kwargs):
if self._sealed:
return
super(class_w, self).__init__(*args, **kwargs)
self._sealed = True
class_w.__name__ = class_.__name__
return class_w

@singleton
class MyClass(BaseClass):
pass

import

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# mysingleton.py


class My_Singleton(object):
def foo(self):
pass

my_singleton = My_Singleton()


# to use
from mysingleton import my_singleton

my_singleton.foo()

metaclass

1
2
3
4
5
6
7
8
9
10

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 Myclass(metaclass=Sigleton):
pass