miércoles 12 de enero de 2011

Design Patterns in python : Singleton

Singleton design pattern provides a mechanism to limit the number of the instances of the class to one. Typically such classes are used to manage resources that by their very nature can only exist once.

There are different approaches to singleton pattern in python.

Singleton

class Singleton(object):
  def __init__(cls,*a,**k):
    if not hasattr(cls,'_inst'):
      cls,_inst = super(Singleton,cls).__new__(cls,*a,**k)
    return cls._inst

Problems with subclassing.

Monostate (Borg Pattern by Alex Martelli). Idea : instead of forcing all instances to have the same identity they share state.

class Borg(object):
  _shared_state = {}
  def __new__(cls, *a, **k):
    obj = super(Borg, cls).__new__(cls, *a, **k)
    obj.__dict__ = cls._shared_state
  return obj

No problems with subclassing.

1 comentarios:

swiss watch dijo...

e negase a viajar a Chennai por razones de seguridad, viajará a Sudáfrica.Bluetooth Headphones reviews

Google Analytics Alternative