Show Menu
Cheatography

Python Design Patterns Cheat Sheet by

Singleton

def Singleton(cls):
  _instances = {}
  def getinstance():
    if cls not in _instances:
      _instances[cls] = cls()
    return _instances[cls]
  return getinstance

@Singleton
class Counter(object):
  def __init(self):
    if not hasattr(self ,’val’): self.val = 0
  def get(self): return self.val
  def incr(self): self.val += 1

Factory

@Singleton
class PlayerFactory(object):
  def new(self, name, type):
    if type == ’peasant’:
      return Peasant(name)
    elif type == ’warior’:
      return Warior(name)
    return None

Proxy

class CounterProxy(object):
    def __init__(self, type):
        self.type = type
    def incr(self):
        if self.type == 'W':
            Counter().incr()
    def get(self):
        Counter().get()

Producer

class Producer(Thread):

  def __init__(self, queue, cvs, maxsize=5):
    Thread.__init__(self)
    self.queue = queue
    self.maxsize = maxsize
    self.notfull = cvs[0]
    self.notempty = cvs[1]
    self.terminate = False
    self.counter = 0

  def run(self):
    while not self.terminate:
      sleep(0.1 * randint(0, 10)) # sleep randomly

      self.notfull.acquire()
      while len(self.queue) >= self.maxsize: # full
        print "full queue, waiting"
        self.notfull.wait()
        if self.terminate:
          break
      self.notfull.release()
      self.counter += 1
      self.queue.append(self.counter)
      self.notempty.acquire()
      self.notempty.notify() # notify consumer, a new item
      self.notempty.release()

  def quit(self):
    self.terminate = True
    self.notfull.acquire()
    self.notfull.notify()
    self.notfull.release()
 

Observer

class Subject(object):
    _observers = []
    def register(self, obs):
        self._observers.append(obs)
    def unregister(self, obs):
        self._observers.remove(obs)
    def notify(self):
        for o in self._observers:
            o.update(self)
    def state(self): pass
class Observer(object):
    def update(self, subj): pass
class Clock(Subject):
    def __init__(self):
        self.value = 0
    def state(self):
        return self.value
    def tick(self):
        self.value += 1
        self.notify()
class Person(Observer):
    def update(self, obj):
        print "heyo", obj.state()
a = Person()
b = Clock()
b.register(a)
b.tick()

facade

class AuthFacade(object):
    def __init__(self ,method):
        if method == 'passwd':
            #
        elif method =='oauth':
            #
        elif method =='otp':
            #
        else:
                throw ...
    def auth(self,identity,data):
        #check authentication based on setting

Consumer

class Consumer(Thread):
  def __init__(self, queue, cvs):
    Thread.__init__(self)
    self.queue = queue
    self.notfull = cvs[0]
    self.notempty = cvs[1]
    self.terminate = False
  def run(self):
    while not self.terminate:
      sleep(0.1 * randint(0, 10)) # sleep randomly
      self.notempty.acquire()
      while len(self.queue) == 0: # empty
        print "empty queue, waiting"
        self.notempty.wait()
        if self.terminate:
          break
      self.notempty.release()
      item = self.queue[0]
      del self.queue[0]
      print "consumed ", item
      self.notfull.acquire()
      self.notfull.notify() # notify consumer, a new item
      self.notfull.release()
  def quit(self):
    self.terminate = True
    self.notempty.acquire()
    self.notempty.notify()
    self.notempty.release()
 

patterns

A complex library, tool or system; consisting of many functions and/or classes; probably poorly designed is tried to be accessed. It is hard to read and unders­tand. There are many depend­encies distri­buted in the source, needs many housek­eeping tasks and stages to access. Any change in the system require changes in the whole source code.
Facade­:Define a class implem­enting all details of the librar­y/s­ystem and providing a simple uniform interface. Access the library through this interface.
You need to access a hard to duplicate, limited, probably old class defini­tion. You donot have a chance to improve it or change the interface. Or, you want to have restricted access to methods (autho­riz­ation). Or, you want smarter access like caching.
Proxy: Write a class interface implem­enting functi­ona­lities missing in the original interface.
Objects depending on eachothers states need to be informed when the other encoun­tered a change. Event handling systems.
Observer: Maintain a registry of observing objects in Subject object. When an event occurs, notify the observers.
Create objects from a set of classes. Implem­ent­ation depends on class defini­tions. Introd­uction of new classes and other changes need recomp­ila­tion. Class constr­uctors exposed.
Factory: Use interface functi­ons­/ob­jects to encaps­ulate class names and constr­uctors. Use a interface functions, methods to provide you instances. Rest is handled by polymo­rphism.

Help Us Go Positive!

We offset our carbon usage with Ecologi. Click the link below to help us!

We offset our carbon footprint via Ecologi
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter

          More Cheat Sheets by sercand