Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion abstract_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import random


class PetShop:
"""A pet shop"""

Expand All @@ -22,41 +23,51 @@ def show_pet(self):
print("It says", pet.speak())
print("It eats", self.pet_factory.get_food())


# Stuff that our factory makes

class Dog:
def speak(self):
return "woof"

def __str__(self):
return "Dog"


class Cat:
def speak(self):
return "meow"

def __str__(self):
return "Cat"


# Factory classes

class DogFactory:
def get_pet(self):
return Dog()

def get_food(self):
return "dog food"


class CatFactory:
def get_pet(self):
return Cat()

def get_food(self):
return "cat food"


# Create the proper family
def get_factory():
"""Let's be dynamic!"""
return random.choice([DogFactory, CatFactory])()


# Show pets with various factories
if __name__== "__main__":
if __name__ == "__main__":
shop = PetShop()
for i in range(3):
shop.pet_factory = get_factory()
Expand Down
9 changes: 8 additions & 1 deletion adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,39 @@

import os


class Dog(object):
def __init__(self):
self.name = "Dog"

def bark(self):
return "woof!"


class Cat(object):
def __init__(self):
self.name = "Cat"

def meow(self):
return "meow!"


class Human(object):
def __init__(self):
self.name = "Human"

def speak(self):
return "'hello'"


class Car(object):
def __init__(self):
self.name = "Car"

def make_noise(self, octane_level):
return "vroom%s" % ("!" * octane_level)


class Adapter(object):
"""
Adapts an object by replacing methods.
Expand All @@ -46,6 +51,7 @@ def __getattr__(self, attr):
"""All non-adapted calls are passed to the object"""
return getattr(self.obj, attr)


def main():
objects = []
dog = Dog()
Expand All @@ -55,11 +61,12 @@ def main():
human = Human()
objects.append(Adapter(human, dict(make_noise=human.speak)))
car = Car()
car_noise = lambda : car.make_noise(3)
car_noise = lambda: car.make_noise(3)
objects.append(Adapter(car, dict(make_noise=car_noise)))

for obj in objects:
print("A", obj.name, "goes", obj.make_noise())


if __name__ == "__main__":
main()
2 changes: 1 addition & 1 deletion borg.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ def __init__(self):
def __str__(self):
return self.state


class YourBorg(Borg):
pass

Expand All @@ -33,4 +34,3 @@ class YourBorg(Borg):
print('rm1:', rm1)
print('rm2:', rm2)
print('rm3:', rm3)

13 changes: 9 additions & 4 deletions bridge.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
# http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Bridge_Pattern#Python


# ConcreteImplementor 1/2
class DrawingAPI1:
def drawCircle(self, x, y, radius):
print('API1.circle at {}:{} radius {}'.format(x, y, radius))



# ConcreteImplementor 2/2
class DrawingAPI2:
def drawCircle(self, x, y, radius):
print('API2.circle at {}:{} radius {}'.format(x, y, radius))



# Refined Abstraction
class CircleShape:
def __init__(self, x, y, radius, drawingAPI):
Expand All @@ -25,16 +28,18 @@ def draw(self):
# high-level i.e. Abstraction specific
def resizeByPercentage(self, pct):
self.__radius *= pct



def main():
shapes = (
CircleShape(1, 2, 3, DrawingAPI1()),
CircleShape(5, 7, 11, DrawingAPI2())
)
)

for shape in shapes:
shape.resizeByPercentage(2.5)
shape.draw()


if __name__ == "__main__":
main()
12 changes: 9 additions & 3 deletions builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
https://gist.github.com/420905#file_builder_python.py
"""


# Director
class Director(object):
def __init__(self):
Expand All @@ -19,6 +20,7 @@ def construct_building(self):
def get_building(self):
return self.builder.building


# Abstract Builder
class Builder(object):
def __init__(self):
Expand All @@ -27,21 +29,24 @@ def __init__(self):
def new_building(self):
self.building = Building()


# Concrete Builder
class BuilderHouse(Builder):
def build_floor(self):
self.building.floor ='One'
self.building.floor = 'One'

def build_size(self):
self.building.size = 'Big'


class BuilderFlat(Builder):
def build_floor(self):
self.building.floor ='More than One'
self.building.floor = 'More than One'

def build_size(self):
self.building.size = 'Small'


# Product
class Building(object):
def __init__(self):
Expand All @@ -51,8 +56,9 @@ def __init__(self):
def __repr__(self):
return 'Floor: %s | Size: %s' % (self.floor, self.size)


# Client
if __name__== "__main__":
if __name__ == "__main__":
director = Director()
director.builder = BuilderHouse()
director.construct_building()
Expand Down
8 changes: 7 additions & 1 deletion chain.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,35 @@
# http://www.testingperspective.com/wiki/doku.php/collaboration/chetan/designpatternsinpython/chain-of-responsibilitypattern


class Handler:
def successor(self, successor):
self.successor = successor


class ConcreteHandler1(Handler):
def handle(self, request):
if request > 0 and request <= 10:
print("in handler1")
else:
self.successor.handle(request)


class ConcreteHandler2(Handler):
def handle(self, request):
if request > 10 and request <= 20:
print("in handler2")
else:
self.successor.handle(request)


class ConcreteHandler3(Handler):
def handle(self, request):
if request > 20 and request <= 30:
print("in handler3")
else:
print('end of chain, no handler for {}'.format(request))


class Client:
def __init__(self):
h1 = ConcreteHandler1()
Expand All @@ -38,5 +43,6 @@ def __init__(self):
for request in requests:
h1.handle(request)

if __name__== "__main__":

if __name__ == "__main__":
client = Client()
5 changes: 3 additions & 2 deletions command.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os


class MoveFileCommand(object):
def __init__(self, src, dest):
self.src = src
Expand Down Expand Up @@ -32,5 +33,5 @@ def undo(self):

# and can also be undone on will
for cmd in undo_stack:
undo_stack.pop().undo() # Now it's bar.txt
undo_stack.pop().undo() # and back to foo.txt
undo_stack.pop().undo() # Now it's bar.txt
undo_stack.pop().undo() # and back to foo.txt
31 changes: 18 additions & 13 deletions composite.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,20 @@ def normalize(val):
to a Python object """

if val.find('-') != -1:
val = val.replace('-','_')
val = val.replace('-', '_')

return val


def denormalize(val):
""" De-normalize a string """

if val.find('_') != -1:
val = val.replace('_','-')
val = val.replace('_', '-')

return val


class SpecialDict(dict):
""" A dictionary type which allows direct attribute
access to its keys """
Expand Down Expand Up @@ -64,24 +66,25 @@ def __setattr__(self, name, value):
# New attribute
self[name] = value


class CompositeDict(SpecialDict):
""" A class which works like a hierarchical dictionary.
This class is based on the Composite design-pattern """

ID = 0

def __init__(self, name=''):

if name:
self._name = name
else:
self._name = ''.join(('id#',str(self.__class__.ID)))
self._name = ''.join(('id#', str(self.__class__.ID)))
self.__class__.ID += 1

self._children = []
# Link back to father
self._father = None
self[self._name] = SpecialDict()
self[self._name] = SpecialDict()

def __getattr__(self, name):

Expand All @@ -101,7 +104,8 @@ def __getattr__(self, name):
return child
else:
attr = getattr(self[self._name], name)
if attr: return attr
if attr:
return attr

raise AttributeError('no attribute named %s' % name)

Expand Down Expand Up @@ -306,17 +310,18 @@ def addChild2(self, child):
self._children.append(child)
self.__setChildDict(child)

if __name__=="__main__":

if __name__ == "__main__":
window = CompositeDict('Window')
frame = window.addChild('Frame')
tfield = frame.addChild('Text Field')
tfield.setAttribute('size','20')
tfield.setAttribute('size', '20')

btn = frame.addChild('Button1')
btn.setAttribute('label','Submit')
btn.setAttribute('label', 'Submit')

btn = frame.addChild('Button2')
btn.setAttribute('label','Browse')
btn.setAttribute('label', 'Browse')

# print(window)
# print(window.Frame)
Expand Down
Loading