Skip to content

Commit 701f206

Browse files
committed
Put project in order.
1 parent bde115c commit 701f206

23 files changed

+832
-533
lines changed

abstractfactory.py

Lines changed: 65 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,65 @@
1-
class Klass1:
2-
""" a very simple obj """
3-
def __init__(self):
4-
pass
5-
def hi(self):
6-
print 'hi'
7-
8-
class Factory:
9-
""" base factory that can construct objects in a variety of ways:
10-
* modules ['package1.subpackage',] to be searched for klass
11-
* search global namespace
12-
* create takes a arguement of what type of class to return
13-
* return a default implementation - subclass must define createDefault()
14-
"""
15-
def __init__(self, modules=[]):
16-
self.modules=modules
17-
18-
def createDefault(self):
19-
print dir()
20-
raise NotImplementedError
21-
22-
def create(self, klass=None):
23-
import string
24-
if klass in globals().keys():
25-
if type(globals()[klass]).__name__=='class':
26-
return globals()[klass]()
27-
for module in self.modules:
28-
try:
29-
fromlist = []
30-
if string.find(module, '.'): fromlist = string.split(module, '.')[:-1]
31-
module = __import__(module, globals(), locals(), fromlist)
32-
if hasattr(module, klass): return getattr(module, klass)()
33-
except AttributeError: pass
34-
return self.createDefault()
35-
36-
class MyFactory(Factory):
37-
""" concrete factory that specifies:
38-
* what modules to search for
39-
* implements a createDefault() - which is used if class isnt found
40-
"""
41-
def __init__(self, modules=[]):
42-
Factory.__init__(self,modules)
43-
def createDefault(self):
44-
return Klass1()
45-
46-
47-
#--------much simpler one by mark lutz, http://shell.rmi.net/~lutz/talk.html
48-
def factory(aClass, *args): # varargs tuple
49-
return apply(aClass, args) # call aClass
50-
51-
class Spam:
52-
def doit(self, message):
53-
print message
54-
55-
class Person:
56-
def __init__(self, name, job):
57-
self.name = name
58-
self.job = job
59-
60-
object1 = factory(Spam)
61-
object2 = factory(Person, "Guido", "guru")
1+
"""Implementation of the abstract factory pattern"""
2+
import random
3+
4+
5+
class PetShop:
6+
"""A pet shop"""
7+
8+
def __init__(self, animal_factory=None):
9+
"""pet_factory is our abstract factory. We can set it at will."""
10+
self.pet_factory = animal_factory
11+
12+
def show_pet(self):
13+
"""Creates and shows a pet using the abstract factory"""
14+
pet = self.pet_factory.get_pet()
15+
print "This is a lovely", pet
16+
print "It says", pet.speak()
17+
print "It eats", self.pet_factory.get_food()
18+
19+
# Stuff that our factory makes
20+
21+
22+
class Dog:
23+
def speak(self):
24+
return "woof"
25+
26+
def __str__(self):
27+
return "Dog"
28+
29+
30+
class Cat:
31+
def speak(self):
32+
return "meow"
33+
34+
def __str__(self):
35+
return "Cat"
36+
37+
38+
# Factory classes
39+
class DogFactory:
40+
def get_pet(self):
41+
return Dog()
42+
43+
def get_food(self):
44+
return "dog food"
45+
46+
47+
class CatFactory:
48+
def get_pet(self):
49+
return Cat()
50+
51+
def get_food(self):
52+
return "cat food"
53+
54+
55+
# Create the proper family
56+
def get_factory():
57+
"""Let's be dynamic!"""
58+
return random.choice([DogFactory, CatFactory])()
59+
60+
# Show pets with various factories
61+
shop = PetShop()
62+
for i in range(3):
63+
shop.pet_factory = get_factory()
64+
shop.show_pet()
65+
print "=" * 10

adapter.py

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,25 @@
1-
class Barfooer:
2-
def barfoo(self, bar, foo):
3-
pass
1+
class Adaptee:
2+
def specific_request(self):
3+
return 'Adaptee'
44

5-
# Per instance, by wrapping and delegation
6-
class FoobaringWrapper:
7-
def __init__(self, wrappee):
8-
self.w = wrappee
9-
def foobar(self, foo, bar):
10-
return self.w.barfoo(bar, foo)
5+
class Adapter:
6+
def __init__(self, adaptee):
7+
self.adaptee = adaptee
118

12-
foobarer = FoobaringWrapper(barfooer)
9+
def request(self):
10+
return self.adaptee.specific_request()
1311

14-
# Per-classs by subclassing and self-delegation
15-
class Foobarer(Barfooer):
16-
def foobar(self,foo, bar):
17-
return self.barfoo(bar, foo)
12+
client = Adapter(Adaptee())
13+
print client.request()
1814

19-
foobarer = Foobarer(some, init, params)
15+
# --------- Second example (by Alex Martelli)------------
2016

17+
class UppercasingFile:
18+
def __init__(self, *a, **k):
19+
self.f = file(*a, **k)
20+
21+
def write(self, data):
22+
self.f.write(data.upper())
23+
24+
def __getattr__(self, name):
25+
return getattr(self.f, name)

bridge.py

Lines changed: 58 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,60 @@
1-
class AbstractParser:
2-
def __init__(self, scanner):
3-
self.scanner = scanner
41

5-
class ExprParser(AbstractParser):
6-
def expr(self):
7-
t = self.scanner.next()...
8-
self.scanner.push_back(t)...
92

3+
# Implementor
4+
class DrawingAPI:
5+
def drawCircle(x, y, radius):
6+
pass
7+
8+
9+
# ConcreteImplementor 1/2
10+
class DrawingAPI1(DrawingAPI):
11+
def drawCircle(self, x, y, radius):
12+
print "API1.circle at %f:%f radius %f" % (x, y, radius)
13+
14+
15+
# ConcreteImplementor 2/2
16+
class DrawingAPI2(DrawingAPI):
17+
def drawCircle(self, x, y, radius):
18+
print "API2.circle at %f:%f radius %f" % (x, y, radius)
19+
20+
21+
# Abstraction
22+
class Shape:
23+
# Low-level
24+
def draw(self):
25+
pass
26+
27+
# High-level
28+
def resizeByPercentage(self, pct):
29+
pass
30+
31+
32+
# Refined Abstraction
33+
class CircleShape(Shape):
34+
def __init__(self, x, y, radius, drawingAPI):
35+
self.__x = x
36+
self.__y = y
37+
self.__radius = radius
38+
self.__drawingAPI = drawingAPI
39+
40+
# low-level i.e. Implementation specific
41+
def draw(self):
42+
self.__drawingAPI.drawCircle(self.__x, self.__y, self.__radius)
43+
44+
# high-level i.e. Abstraction specific
45+
def resizeByPercentage(self, pct):
46+
self.__radius *= pct
47+
48+
49+
def main():
50+
shapes = [
51+
CircleShape(1, 2, 3, DrawingAPI1()),
52+
CircleShape(5, 7, 11, DrawingAPI2())
53+
]
54+
55+
for shape in shapes:
56+
shape.resizeByPercentage(2.5)
57+
shape.draw()
58+
59+
if __name__ == "__main__":
60+
main()

chainofresp.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Car:
2+
def __init__(self):
3+
self.name = None
4+
self.km = 11100
5+
self.fuel = 5
6+
self.oil = 5
7+
8+
9+
def handle_fuel(car):
10+
if car.fuel < 10:
11+
print "added fuel"
12+
car.fuel = 100
13+
14+
15+
def handle_km(car):
16+
if car.km > 10000:
17+
print "made a car test."
18+
car.km = 0
19+
20+
21+
def handle_oil(car):
22+
if car.oil < 10:
23+
print "Added oil"
24+
car.oil = 100
25+
26+
27+
class Garage:
28+
def __init__(self):
29+
self.handlers = []
30+
31+
def add_handler(self, handler):
32+
self.handlers.append(handler)
33+
34+
def handle_car(self, car):
35+
for handler in self.handlers:
36+
handler(car)
37+
38+
if __name__ == '__main__':
39+
handlers = [handle_fuel, handle_km, handle_oil]
40+
garage = Garage()
41+
42+
for handle in handlers:
43+
garage.add_handler(handle)
44+
garage.handle_car(Car())

closure.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,6 @@ def dfdx(x):
66
def f(x):
77
return 3*x**2+x
88

9-
"""
10-
>>> print f(1.0)
11-
4.0
12-
>>> print Dx(f, 0.01)(1.0)
13-
7.03
14-
>>> print Dx(Dx(f, 0.01), 0.01)(1.0)
15-
"""
9+
print f(1.0) # 4.0
10+
print Dx(f, 0.01)(1.0) # 7.03
11+
print Dx(Dx(f, 0.01), 0.01)(1.0)

0 commit comments

Comments
 (0)