Skip to content

Commit bfa3e09

Browse files
committed
Added singleton pattern with overriding __new__ method.
1 parent 6f9c75c commit bfa3e09

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ __Creational Patterns__:
2020
| [lazy_evaluation](lazy_evaluation.py) | lazily-evaluated property pattern in Python |
2121
| [pool](pool.py) | preinstantiate and maintain a group of instances of the same type |
2222
| [prototype](prototype.py) | use a factory and clones of a prototype for new instances (if instantiation is expensive) |
23+
| [singleton](singleton.py) | a singleton with overriding __new__ method |
2324

2425
__Structural Patterns__:
2526

singleton.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
5+
class Singleton(object):
6+
"""
7+
Assume that only one instance should be created of this class and
8+
it is counting the users connected to the system.
9+
"""
10+
11+
_instance = None
12+
13+
def __new__(cls, *args, **kwargs):
14+
"""
15+
For each class, creating only one instance.
16+
If an instance has been created before, returns the created one.
17+
"""
18+
if not cls._instance:
19+
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
20+
21+
# your init codes here
22+
cls.user_count = 0
23+
# end of your init code
24+
25+
return cls._instance
26+
27+
def connect(self):
28+
self.user_count += 1
29+
30+
def disconnect(self):
31+
self.user_count -= 1
32+
33+
34+
if __name__ == '__main__':
35+
36+
s1 = Singleton()
37+
s2 = Singleton()
38+
39+
if id(s1) == id(s2):
40+
print "Same instances"
41+
else:
42+
print "Different instances"
43+
44+
s1.connect() # user count: 1
45+
s1.connect() # user count: 2
46+
s2.connect() # same instance with s1, so user count: 3 for s1 and s2
47+
s1.disconnect() # same instance with s2, so user count: 2 for s1 and s2
48+
49+
print s1.user_count
50+
print s2.user_count

0 commit comments

Comments
 (0)