0% found this document useful (0 votes)
2 views2 pages

Python Design Patterns BW

This document is a cheat sheet for Python design patterns, covering various patterns such as Singleton, Factory, Observer, Facade, and Proxy. It provides code snippets and explanations for implementing these patterns in Python, including examples of TCP and UDP server/client communication. The document serves as a quick reference for developers looking to understand and apply design patterns in their Python projects.

Uploaded by

knlklabacka
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Python Design Patterns BW

This document is a cheat sheet for Python design patterns, covering various patterns such as Singleton, Factory, Observer, Facade, and Proxy. It provides code snippets and explanations for implementing these patterns in Python, including examples of TCP and UDP server/client communication. The document serves as a quick reference for developers looking to understand and apply design patterns in their Python projects.

Uploaded by

knlklabacka
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Design Patterns Cheat Sheet

by sercand via [Link]/32560/cs/10035/

Singleton Producer (cont) TCP Server​/Client (cont)

def Singleton(cls): ​ ​ ​ ​sel​f.n​otfull = cvs[0] [Link]​en(1)


​ ​_in​stances = {} ​ ​ ​ ​sel​f.n​otempty = cvs[1] while True:
​ def getins​tan​ce(): ​ ​ ​ ​sel​f.t​erm​inate = False ​ ​ ​ ​conn, addr = [Link]()
​ ​ ​ if cls not in _insta​nces: ​ ​ ​ ​sel​f.c​ounter = 0 ​ ​ ​ ​print 'Connected by', addr
​ ​ ​ ​ ​ ​_in​sta​nce​s[cls] = cls() ​ def run(self): ​ ​ ​ ​while True:
​ ​ ​ ​return _insta​nce​s[cls] ​ ​ ​ ​while not self.t​erm​inate: ​ ​ ​ ​ ​ ​ ​ data = conn.r​ecv​(1024)
​ ​return getins​tance ​ ​ ​ ​ ​ ​sle​ep(0.1 * randint(0, 10)) ​ ​ ​ ​ ​ ​ ​ if not data:
@Singleton # sleep randomly ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​break
class Counte​r(o​bject): ​ ​ ​ ​ ​ ​sel​f.n​otf​[Link]​quire() ​ ​ ​ ​ ​ ​ ​ ​con​n.s​end​(data)
​ def __init​(self): ​ ​ ​ ​ ​ ​while len(se​lf.q​ueue) >= ​ ​ ​ ​con​n.c​lose()
​ ​ ​ if not hasatt​r(self ,’val’): self.m​axsize: # full
[Link] = 0 ​ ​ ​ ​ ​ ​ ​ ​print "full queue, Observer
​ def get(self): return [Link] waitin​g"
class Subject(object):
​ def incr(s​elf): [Link] += 1 ​ ​ ​ ​ ​ ​ ​ ​sel​f.n​otf​[Link]()
​ ​ ​ ​_ob​servers = []
​ ​ ​ ​ ​ ​ ​ if self.t​erm​inate:
​ ​ ​ def regist​er(​self, obs):
Factory ​ ​ ​ ​ ​ ​ ​ ​ ​ ​break
​ ​ ​ ​ ​ ​ ​ ​sel​f._​obs​erv​[Link]​pen​d(obs)
​ ​ ​ ​ ​ ​sel​f.n​otf​[Link]​lease()
@Singleton ​ ​ ​ def unregi​ste​r(self, obs):
​ ​ ​ ​ ​ ​sel​f.c​ounter += 1
class Player​Fac​tor​y(o​bject): ​ ​ ​ ​ ​ ​ ​ ​sel​f._​obs​erv​[Link]​mov​e(obs)
​ ​ ​ ​ ​ ​sel​f.q​ueu​e.a​ppe​nd(​sel​f.c​ounte
​ def new(self, name, type): ​ ​ ​ def notify​(self):
r)
​ ​ ​ if type == ’peasant’: ​ ​ ​ ​ ​ ​ ​ for o in self._​obs​ervers:
​ ​ ​ ​ ​ ​sel​f.n​ote​mpt​y.a​cqu​ire()
​ ​ ​ ​ ​ ​return Peasan​t(name) ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​o.u​pda​te(​self)
​ ​ ​ ​ ​ ​sel​f.n​ote​mpt​y.n​otify() #
​ ​ ​ elif type == ’warior’: ​ ​ ​ def state(​self): pass
notify consumer, a new item
​ ​ ​ ​ ​ ​return Warior​(name) class Observ​er(​obj​ect):
​ ​ ​ ​ ​ ​sel​f.n​ote​mpt​y.r​ele​ase()
​ ​ ​ ​return None ​ ​ ​ def update​(self, subj): pass
​ def quit(s​elf):
class Clock(​Sub​ject):
​ ​ ​ ​sel​f.t​erm​inate = True
Proxy ​ ​ ​ def __init​__(​self):
​ ​ ​ ​sel​f.n​otf​[Link]​quire()
​ ​ ​ ​ ​ ​ ​ ​sel​[Link] = 0
class CounterProxy(object):
​ ​ ​ ​sel​f.n​otf​[Link]​tify()
​ ​ ​ def state(​self):
​ ​ ​ def __init​__(​self, type):
​ ​ ​ ​sel​f.n​otf​[Link]​lease()
​ ​ ​ ​ ​ ​ ​ ​return [Link]
​ ​ ​ ​ ​ ​ ​ ​sel​[Link] = type
​ ​ ​ def tick(s​elf):
​ ​ ​ def incr(s​elf):
TCP Server​/Client
​ ​ ​ ​ ​ ​ ​ ​sel​[Link] += 1
​ ​ ​ ​ ​ ​ ​ if [Link] == 'W':
#Client ​ ​ ​ ​ ​ ​ ​ ​sel​f.n​otify()
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​Cou​nte​r().incr()
s = [Link]​cke​t(s​ock​et.A​F_​INET, class Person​(Ob​ser​ver):
​ ​ ​ def get(self):
[Link]​CK_​STREAM) ​ ​ ​ def update​(self, obj):
​ ​ ​ ​ ​ ​ ​ ​Cou​nte​r().get()
[Link]​ect​(('​[Link]', 50007)) ​ ​ ​ ​ ​ ​ ​ ​print "​hey​o", [Link]​ate()
[Link]​('H​ello') a = Person()
Producer
data = [Link]​(1024) b = Clock()
class Producer(Thread):
print 'Recei​ved', repr(data) [Link]​ster(a)
​ def __init​__(​self, queue, cvs,
[Link]() [Link]()
maxsiz​e=5):
#Server
​ ​ ​ ​Thr​ead.__​ini​t__​(self)
s = [Link]​cke​t(s​ock​et.A​F_​INET,
​ ​ ​ ​sel​[Link] = queue
[Link]​CK_​STREAM)
​ ​ ​ ​sel​f.m​axsize = maxsize
[Link]​(('', 50007))

By sercand Published 2nd December, 2016. Sponsored by [Link]


[Link]/sercand/ Last updated 2nd December, 2016. Measure your website readability!
Page 1 of 2. [Link]
Python Design Patterns Cheat Sheet
by sercand via [Link]/32560/cs/10035/

facade Consumer (cont) patterns (cont)

class AuthFacade(object): ​ ​ ​ ​sel​f.t​erm​inate = True Objects depending on Observer: Maintain a


​ ​ ​ def __init​__(self ,method): ​ ​ ​ ​sel​f.n​ote​mpt​y.a​cqu​ire() eachothers states registry of observing
need to be informed objects in Subject
​ ​ ​ ​ ​ ​ ​ if method == 'passwd': ​ ​ ​ ​sel​f.n​ote​mpt​y.n​otify()
when the other object. When an event
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ # ​ ​ ​ ​sel​f.n​ote​mpt​y.r​ele​ase()
encoun​tered a occurs, notify the
​ ​ ​ ​ ​ ​ ​ elif method =='oauth':
change. Event observers.
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ # patterns handling systems.
​ ​ ​ ​ ​ ​ ​ elif method =='otp':
A complex library, tool or Facade​:Defin Create objects from a Factory: Use interface
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ # system; consisting of many e a class set of classes. functi​ons​/ob​jects to
​ ​ ​ ​ ​ ​ ​ ​else: functions and/or classes; implem​entin Implem​ent​ation encaps​ulate class
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​throw ... probably poorly designed is g all details depends on class names and

​ ​ ​ def auth(s​elf​,id​ent​ity​,data): tried to be accessed. It is hard of the defini​tions. constr​uctors. Use a


to read and unders​tand. There librar​y/s​yste Introd​uction of new interface functions,
​ ​ ​ ​ ​ ​ ​ ​#check authen​tic​ation based
are many depend​encies m and classes and other methods to provide
on setting
distri​buted in the source, needs providing a changes need you instances. Rest is
many housek​eeping tasks and simple recomp​ila​tion. Class handled by
Consumer stages to access. Any change uniform constr​uctors exposed. polymo​rphism.
in the system require changes in interface.
class Consumer(Thread):
the whole source code. Access the UDP Server​-Client (not design pattern)
​ def __init​__(​self, queue, cvs):
library
​ ​ ​ ​Thr​ead.__​ini​t__​(self) #Client
through this
​ ​ ​ ​sel​[Link] = queue interface. s = [Link]​cke​t(s​ock​et.A​F_​INET,
​ ​ ​ ​sel​f.n​otfull = cvs[0] You need to access a hard to Proxy: Write [Link]​CK_​DGRAM)
​ ​ ​ ​sel​f.n​otempty = cvs[1] duplicate, limited, probably old a class [Link]​(('​[Link]', 20001))
​ ​ ​ ​sel​f.t​erm​inate = False class defini​tion. You donot have interface [Link]​to(​"​hel​lo", ('loca​lhost',
​ def run(self): a chance to improve it or implem​entin 20000))
​ ​ ​ ​while not self.t​erm​inate: change the interface. Or, you g (data, addr) = [Link]​fro​m(1024)
want to have restricted access functi​ona​litie
​ ​ ​ ​ ​ ​sle​ep(0.1 * randint(0, 10)) # print 'server responded: ', data
to methods (autho​riz​ation). Or, s missing in
sleep randomly [Link]()
you want smarter access like the original
​ ​ ​ ​ ​ ​sel​f.n​ote​mpt​y.a​cqu​ire() caching. interface. #Server
​ ​ ​ ​ ​ ​while len(se​lf.q​ueue) == 0: # s = [Link]​cke​t(s​ock​et.A​F_​INET,
empty [Link]​CK_​DGRAM)
​ ​ ​ ​ ​ ​ ​ ​print "​empty queue, [Link]​(('​[Link]', 20000))
waitin​g" while True:
​ ​ ​ ​ ​ ​ ​ ​sel​f.n​ote​mpt​y.w​ait() ​ ​ ​ ​(data, addr) =
​ ​ ​ ​ ​ ​ ​ if self.t​erm​inate: [Link]​fro​m(1024)
​ ​ ​ ​ ​ ​ ​ ​ ​ ​break ​ ​ ​ ​s.s​end​to(​"​out​put​", addr)
​ ​ ​ ​ ​ ​sel​f.n​ote​mpt​y.r​ele​ase()
​ ​ ​ ​ ​ item = self.q​ueue[0]
​ ​ ​ ​ ​ del self.q​ueue[0]
​ ​ ​ ​ ​ ​print "​con​sumed ", item
​ ​ ​ ​ ​ ​sel​f.n​otf​[Link]​quire()
​ ​ ​ ​ ​ ​sel​f.n​otf​[Link]​tify() #
notify consumer, a new item
​ ​ ​ ​ ​ ​sel​f.n​otf​[Link]​lease()
​ def quit(s​elf):

By sercand Published 2nd December, 2016. Sponsored by [Link]


[Link]/sercand/ Last updated 2nd December, 2016. Measure your website readability!
Page 2 of 2. [Link]

You might also like