File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff 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
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments