Python singleton instantiation

来源:互联网 发布:mysql入门经典 pdf 编辑:程序博客网 时间:2024/05/17 23:37

  • Creational Patterns

    A creational pattern provides a particular instantiation mechanism. It can be aparticular object factory or even a class factory.

    This is an important pattern in compiled languages such as C, since it is harder togenerate types on-demand at run time.

page343image432

Useful Design Patterns

But this feature is built-in in Python, for instance thetype built-in, which lets youdefine a new type by code:

   >>> MyType = type('MyType', (object,), {'a': 1})   >>> ob = MyType()   >>> type(ob)   <class '__main__.MyType'>
   >>> ob.a   1   >>> isinstance(ob, object)   True

Classes and types are built-in factories and you can interact with class and objectgeneration using meta-classes, for instance (see Chapter 3). These features are thebasics to implement theFactorydesign pattern and we won't further describe it inthis section.

Besides Factory, the only other creational design pattern from the GoF that isinteresting to describe in Python isSingleton.

Singleton

Singleton restricts instantiation of a class to one object.

The Singleton pattern makes sure that a given class has always only one livinginstance in the application. This can be used, for example, when you want to restricta resource access to one and only one memory context in the process. For instance,a database connector class can be a Singleton that deals with synchronization andmanages its data in memory. It makes the assumption that no other instance isinteracting with the database in the meantime.

This pattern can simplify a lot the way concurrency is handled in an application.Utilities that provide application-wide functions are often declared as Singletons.For instance, in web applications, a class that is in charge of reserving a uniquedocument ID would benefit from the Singleton pattern. There should be one andonly one utility doing this job.

Implementing the Singleton pattern is straightforward with the__new__ method:>>> class Singleton(object):

page343image16032page343image16192page343image16616page343image17040

.........

def __new__(cls, *args, **kw):    if not hasattr(cls, '_instance'):
     orig = super(Singleton, cls)

[ 326 ]

page343image25024page343image25184
page344image416
...             cls._instance = orig.__new__(cls, *args, **kw)...         return cls._instance...>>> class MyClass(Singleton):

... a =1
...
>>> one = MyClass()>>> two = MyClass()>>> two.a = 3
>>> one.a
3

Although the problem with this pattern is subclassing; all instances will be instancesofMyClass no matter what the method resolution order (__mro__) says:

>>> class MyOtherClass(MyClass):... b= 2
...
>>> three = MyOtherClass()

   >>> three.b   Traceback (most recent call last):
     File "<stdin>", line 1, in ?   AttributeError: 'MyClass' object has no attribute 'b'

To avoid this limitation, Alex Martelli proposed an alternative implementation basedon shared state calledBorg.

The idea is quite simple. What really matters in the Singleton pattern is not thenumber of living instances a class has, but rather the fact that they all share the samestate at all times. So Alex Martelli came up with a class that makes all instances of theclass share the same__dict__:

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

... a =1
...
>>> one = MyClass()>>> two = MyClass()>>> two.a = 3
>>> one.a

[ 327 ]

Chapter 14

page344image15976page344image16136page344image16296
page345image424

Useful Design Patterns

3
>>> class MyOtherClass(MyClass):... b= 2
...
>>> three = MyOtherClass()
>>> three.b
2
>>> three.a
3
>>> three.a = 2
>>> one.a
2

This fixes the subclassing issue, but is still dependent on how the subclass codeworks. For instance, if__getattr__ is overridden, the pattern can be broken.

Nevertheless, Singletons should not have several levels of inheritance. A class that ismarked as a Singleton is already specific.

That said, this pattern is considered by many developers as a heavy way to deal withuniqueness in an application. If a Singleton is needed, why not use a module withfunctions instead, since a Python module is a Singleton?

The Singleton factory is an implicit way of dealing with the uniquenessin your application. You can live without it. Unless you are working in aframework à la Java that requires such a pattern, use a module insteadof a class. 





instantiation

 
英 [ɪnstænʃɪ'eɪʃən]    美 [ɪnstænʃɪ'eɪʃən]   
  • n.实例化;用具体例子说明;例示
释义常用度分布图海词统计
实例化
例示
用具体例..

instantiation是什么意思,词典释义与在线翻译:

行业释义

英英释义

Noun:
  1. a representation of an idea in the form of an instance of it;

    "how many instantiations were found?"

instantiation的用法和样例:

例句

  1. An object is instantiation of a class.
    对象是类的实列。
  2. Needed for instantiation and views.
    听 听 听 听 听-- raw symbol map.
  3. A new rule is created through the instantiation of a template.
    透过范本实例定义新的规则。
  4. Use delegate inference instead of explicit delegate instantiation.
    使用委托定义而不是直接的委托实例。
  5. The target instance to be created on template instantiation.
    将被创建在模板例示上的目标范例。
词性常用度分布图海词统计
名词
去句海,查更多例句»

0 0
原创粉丝点击