Python Design Patterns Cheat Sheet
by sercand via [Link]/32560/cs/10035/
Singleton Producer (cont) TCP Server/Client (cont)
def Singleton(cls): self.notfull = cvs[0] [Link]en(1)
_instances = {} self.notempty = cvs[1] while True:
def getinstance(): self.terminate = False conn, addr = [Link]()
if cls not in _instances: self.counter = 0 print 'Connected by', addr
_instances[cls] = cls() def run(self): while True:
return _instances[cls] while not self.terminate: data = conn.recv(1024)
return getinstance sleep(0.1 * randint(0, 10)) if not data:
@Singleton # sleep randomly break
class Counter(object): self.notf[Link]quire() conn.send(data)
def __init(self): while len(self.queue) >= conn.close()
if not hasattr(self ,’val’): self.maxsize: # full
[Link] = 0 print "full queue, Observer
def get(self): return [Link] waiting"
class Subject(object):
def incr(self): [Link] += 1 self.notf[Link]()
_observers = []
if self.terminate:
def register(self, obs):
Factory break
self._observ[Link]pend(obs)
self.notf[Link]lease()
@Singleton def unregister(self, obs):
self.counter += 1
class PlayerFactory(object): self._observ[Link]move(obs)
self.queue.append(self.counte
def new(self, name, type): def notify(self):
r)
if type == ’peasant’: for o in self._observers:
self.notempty.acquire()
return Peasant(name) o.update(self)
self.notempty.notify() #
elif type == ’warior’: def state(self): pass
notify consumer, a new item
return Warior(name) class Observer(object):
self.notempty.release()
return None def update(self, subj): pass
def quit(self):
class Clock(Subject):
self.terminate = True
Proxy def __init__(self):
self.notf[Link]quire()
sel[Link] = 0
class CounterProxy(object):
self.notf[Link]tify()
def state(self):
def __init__(self, type):
self.notf[Link]lease()
return [Link]
sel[Link] = type
def tick(self):
def incr(self):
TCP Server/Client
sel[Link] += 1
if [Link] == 'W':
#Client self.notify()
Counter().incr()
s = [Link]cket(socket.AF_INET, class Person(Observer):
def get(self):
[Link]CK_STREAM) def update(self, obj):
Counter().get()
[Link]ect(('[Link]', 50007)) print "heyo", [Link]ate()
[Link]('Hello') a = Person()
Producer
data = [Link](1024) b = Clock()
class Producer(Thread):
print 'Received', repr(data) [Link]ster(a)
def __init__(self, queue, cvs,
[Link]() [Link]()
maxsize=5):
#Server
Thread.__init__(self)
s = [Link]cket(socket.AF_INET,
sel[Link] = queue
[Link]CK_STREAM)
self.maxsize = 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): self.terminate = True Objects depending on Observer: Maintain a
def __init__(self ,method): self.notempty.acquire() eachothers states registry of observing
need to be informed objects in Subject
if method == 'passwd': self.notempty.notify()
when the other object. When an event
# self.notempty.release()
encountered 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. functions/objects to
else: functions and/or classes; implementin Implementation encapsulate class
throw ... probably poorly designed is g all details depends on class names and
def auth(self,identity,data): tried to be accessed. It is hard of the definitions. constructors. Use a
to read and understand. There library/syste Introduction of new interface functions,
#check authentication based
are many dependencies m and classes and other methods to provide
on setting
distributed in the source, needs providing a changes need you instances. Rest is
many housekeeping tasks and simple recompilation. Class handled by
Consumer stages to access. Any change uniform constructors exposed. polymorphism.
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
Thread.__init__(self) #Client
through this
sel[Link] = queue interface. s = [Link]cket(socket.AF_INET,
self.notfull = cvs[0] You need to access a hard to Proxy: Write [Link]CK_DGRAM)
self.notempty = cvs[1] duplicate, limited, probably old a class [Link](('[Link]', 20001))
self.terminate = False class definition. You donot have interface [Link]to("hello", ('localhost',
def run(self): a chance to improve it or implementin 20000))
while not self.terminate: change the interface. Or, you g (data, addr) = [Link]from(1024)
want to have restricted access functionalitie
sleep(0.1 * randint(0, 10)) # print 'server responded: ', data
to methods (authorization). Or, s missing in
sleep randomly [Link]()
you want smarter access like the original
self.notempty.acquire() caching. interface. #Server
while len(self.queue) == 0: # s = [Link]cket(socket.AF_INET,
empty [Link]CK_DGRAM)
print "empty queue, [Link](('[Link]', 20000))
waiting" while True:
self.notempty.wait() (data, addr) =
if self.terminate: [Link]from(1024)
break s.sendto("output", addr)
self.notempty.release()
item = self.queue[0]
del self.queue[0]
print "consumed ", item
self.notf[Link]quire()
self.notf[Link]tify() #
notify consumer, a new item
self.notf[Link]lease()
def quit(self):
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]