Both methods singletons to realize a small circle ape's python

Small ape circle method alex talked about several ways to achieve Singleton pattern, small series the most classic, most often with two single-case model presented to you, if you want to learn other singleton, you can go small ape circle look alex of course , to learn about.

Singleton name suggests is an instance of this class can only create, how to create it?

1, __ new__ single-Example:

. 1   class Foo (Object):
 2    DEF  the __init__ (Self, name):
 . 3  
. 4      the self.name = name
 . 5  
. 6    DEF  __new__ is (CLS, args *, ** kwargs):
 . 7  
. 8      IF  Not the hasattr (CLS, instance): # Object instance attribute is absent 
. 9  
10        cls.instance Super = (). __new__ is (CLS, args *, ** kwargs)
 . 11  
12 is      return cls.instance # creates an instance, not to initialize the object 
13 is  
14 F = Foo ( ' Hello ' )
 15 
16 f1=Foo('hi')
17 
18 f.name=hello f1.name=hi
19 
20 id(f)==id(f1)

Address has not changed property changed

2, implemented using a single embodiment of the decorative:

. 1    class Demo (CLS, AGS *, ** kwargs):
 2    instance = {}
 . 3  
. 4    DEF foo (* args, ** kwargs):
 . 5  
. 6      IF CLS Not  in instance:
 . 7  
. 8        instance [CLS] = CLS (* args, ** kwargs) # specific examples (a good example of objects initialized) 
. 9  
10      return instance [CLS]
 . 11  
12 is      return foo
 13 is  
14  @Demo
 15  
16  class School (Object):
 . 17  
18 is    DEF  the __init__ (Self, name)
 19 
20   self.name=name
21 
22 s=School('hafo')
23 
24 s1=School('qinghua')
25 
26 s.name=hafo s1.name=hafo s1==s

Address has not changed, the property has not changed

Friends see both similarities and differences to achieve a single case yet? Although both can achieve a singleton, but __new__ singleton implemented, although only achieve one instance but the property has changed, Singleton decorator implemented, can ensure that id attribute and remain one, if my friends on the other between different interest singleton, you can go to a small circle ape look at the contents alex talking about single-case realization.

Guess you like

Origin www.cnblogs.com/xiaoyuanquan/p/10943782.html