Permalink
Browse files

initial commit

  • Loading branch information...
1 parent 909cbb9 commit 00028ad8b4a3c4f38d0d8175cd89341c2e778ecf Sakis Kasampalis committed Jun 6, 2012
Showing with 1,470 additions and 0 deletions.
  1. +64 −0 abstract_factory.py
  2. +65 −0 adapter.py
  3. +24 −0 borg.py
  4. +40 −0 bridge.py
  5. +64 −0 builder.py
  6. +42 −0 chain.py
  7. +36 −0 command.py
  8. +326 −0 composite.py
  9. +21 −0 decorator.py
  10. +58 −0 facade.py
  11. +29 −0 factory_method.py
  12. +31 −0 flyweight.py
  13. +25 −0 iterator.py
  14. +111 −0 mediator.py
  15. +91 −0 memento.py
  16. +78 −0 null.py
  17. +76 −0 observer.py
  18. +49 −0 pool.py
  19. +33 −0 prototype.py
  20. +29 −0 proxy.py
  21. +58 −0 state.py
  22. +32 −0 strategy.py
  23. +50 −0 template.py
  24. +38 −0 visitor.py
View
@@ -0,0 +1,64 @@
+# http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
+
+"""Implementation of the abstract factory pattern"""
+
+import random
+
+class PetShop:
+ """A pet shop"""
+
+ def __init__(self, animal_factory=None):
+ """pet_factory is our abstract factory.
+ We can set it at will."""
+
+ self.pet_factory = animal_factory
+
+ def show_pet(self):
+ """Creates and shows a pet using the
+ abstract factory"""
+
+ pet = self.pet_factory.get_pet()
+ print("This is a lovely", pet)
+ 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__":
+ shop = PetShop()
+ for i in range(3):
+ shop.pet_factory = get_factory()
+ shop.show_pet()
+ print("=" * 20)
View
@@ -0,0 +1,65 @@
+# http://ginstrom.com/scribbles/2008/11/06/generic-adapter-class-in-python/
+
+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.
+ Usage:
+ dog = Dog
+ dog = Adapter(dog, dict(make_noise=dog.bark))
+ """
+ def __init__(self, obj, adapted_methods):
+ """We set the adapted methods in the object's dict"""
+ self.obj = obj
+ self.__dict__.update(adapted_methods)
+
+ def __getattr__(self, attr):
+ """All non-adapted calls are passed to the object"""
+ return getattr(self.obj, attr)
+
+def main():
+ objects = []
+ dog = Dog()
+ objects.append(Adapter(dog, dict(make_noise=dog.bark)))
+ cat = Cat()
+ objects.append(Adapter(cat, dict(make_noise=cat.meow)))
+ human = Human()
+ objects.append(Adapter(human, dict(make_noise=human.speak)))
+ car = Car()
+ 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()
View
@@ -0,0 +1,24 @@
+class Borg:
+ __shared_state = {}
+
+ def __init__(self):
+ self.__dict__ = self.__shared_state
+ self.state = 'Running'
+
+ def __str__(self):
+ return self.state
+
+if __name__ == '__main__':
+ rm1 = Borg()
+ rm2 = Borg()
+
+ print('rm1 state: {}'.format(rm1))
+ print('rm2 state: {}'.format(rm2))
+
+ rm2.state = 'Idle'
+
+ print('rm1 state: {}'.format(rm1))
+ print('rm2 state: {}'.format(rm2))
+
+ print('rm1 id: {}', id(rm1))
+ print('rm2 id: {}', id(rm2))
View
@@ -0,0 +1,40 @@
+# 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):
+ self.__x = x
+ self.__y = y
+ self.__radius = radius
+ self.__drawingAPI = drawingAPI
+
+ # low-level i.e. Implementation specific
+ def draw(self):
+ self.__drawingAPI.drawCircle(self.__x, self.__y, self.__radius)
+
+ # 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()
View
@@ -0,0 +1,64 @@
+#!/usr/bin/python
+# -*- coding : utf-8 -*-
+
+"""
+ @author: Diogenes Augusto Fernandes Herminio <diofeher@gmail.com>
+ https://gist.github.com/420905#file_builder_python.py
+"""
+
+# Director
+class Director(object):
+ def __init__(self):
+ self.builder = None
+
+ def construct_building(self):
+ self.builder.new_building()
+ self.builder.build_floor()
+ self.builder.build_size()
+
+ def get_building(self):
+ return self.builder.building
+
+# Abstract Builder
+class Builder(object):
+ def __init__(self):
+ self.building = None
+
+ def new_building(self):
+ self.building = Building()
+
+# Concrete Builder
+class BuilderHouse(Builder):
+ def build_floor(self):
+ 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'
+
+ def build_size(self):
+ self.building.size = 'Small'
+
+# Product
+class Building(object):
+ def __init__(self):
+ self.floor = None
+ self.size = None
+
+ def __repr__(self):
+ return 'Floor: %s | Size: %s' % (self.floor, self.size)
+
+# Client
+if __name__== "__main__":
+ director = Director()
+ director.builder = BuilderHouse()
+ director.construct_building()
+ building = director.get_building()
+ print(building)
+ director.builder = BuilderFlat()
+ director.construct_building()
+ building = director.get_building()
+ print(building)
View
@@ -0,0 +1,42 @@
+# 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()
+ h2 = ConcreteHandler2()
+ h3 = ConcreteHandler3()
+
+ h1.successor(h2)
+ h2.successor(h3)
+
+ requests = [2, 5, 14, 22, 18, 3, 35, 27, 20]
+ for request in requests:
+ h1.handle(request)
+
+if __name__== "__main__":
+ client = Client()
View
@@ -0,0 +1,36 @@
+import os
+
+class MoveFileCommand(object):
+ def __init__(self, src, dest):
+ self.src = src
+ self.dest = dest
+
+ def execute(self):
+ self()
+
+ def __call__(self):
+ print('renaming {} to {}'.format(self.src, self.dest))
+ os.rename(self.src, self.dest)
+
+ def undo(self):
+ print('renaming {} to {}'.format(self.dest, self.src))
+ os.rename(self.dest, self.src)
+
+
+if __name__ == "__main__":
+ undo_stack = []
+ ren1 = MoveFileCommand('foo.txt', 'bar.txt')
+ ren2 = MoveFileCommand('bar.txt', 'baz.txt')
+
+ # commands are just pushed into the command stack
+ for cmd in ren1, ren2:
+ undo_stack.append(cmd)
+
+ # they can be executed later on will
+ for cmd in undo_stack:
+ cmd.execute() # foo.txt is now renamed to baz.txt
+
+ # 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
Oops, something went wrong.

0 comments on commit 00028ad

Please sign in to comment.