Show Menu

Python Design Patterns Cheat Sheet by


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

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


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


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


class Producer(Thread):

  def __init__(self, queue, cvs, maxsize=5):
    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

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

  def quit(self):
    self.terminate = True


class Subject(object):
    _observers = []
    def register(self, obs):
    def unregister(self, obs):
    def notify(self):
        for o in self._observers:
    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
class Person(Observer):
    def update(self, obj):
        print "heyo", obj.state()
a = Person()
b = Clock()


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


class Consumer(Thread):
  def __init__(self, queue, cvs):
    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
      while len(self.queue) == 0: # empty
        print "empty queue, waiting"
        if self.terminate:
      item = self.queue[0]
      del self.queue[0]
      print "consumed ", item
      self.notfull.notify() # notify consumer, a new item
  def quit(self):
    self.terminate = True


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


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