Skip to content

Commit bde115c

Browse files
committed
Added new implementations.
1 parent bc65ce4 commit bde115c

12 files changed

+381
-0
lines changed

abstrfactory4.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""Implementation of the abstract factory pattern"""
2+
3+
import random
4+
5+
class PetShop:
6+
"""A pet shop"""
7+
8+
def __init__(self, animal_factory=None):
9+
"""pet_factory is our abstract factory.
10+
We can set it at will."""
11+
12+
self.pet_factory = animal_factory
13+
14+
def show_pet(self):
15+
"""Creates and shows a pet using the
16+
abstract factory"""
17+
18+
pet = self.pet_factory.get_pet()
19+
print "This is a lovely", pet
20+
print "It says", pet.speak()
21+
print "It eats", self.pet_factory.get_food()
22+
23+
# Stuff that our factory makes
24+
25+
class Dog:
26+
def speak(self):
27+
return "woof"
28+
def __str__(self):
29+
return "Dog"
30+
31+
class Cat:
32+
def speak(self):
33+
return "meow"
34+
def __str__(self):
35+
return "Cat"
36+
37+
# Factory classes
38+
39+
class DogFactory:
40+
def get_pet(self):
41+
return Dog()
42+
def get_food(self):
43+
return "dog food"
44+
45+
class CatFactory:
46+
def get_pet(self):
47+
return Cat()
48+
def get_food(self):
49+
return "cat food"
50+
51+
# Create the proper family
52+
def get_factory():
53+
"""Let's be dynamic!"""
54+
return random.choice([DogFactory, CatFactory])()
55+
56+
# Show pets with various factories
57+
shop = PetShop()
58+
for i in range(3):
59+
shop.pet_factory = get_factory()
60+
shop.show_pet()
61+
print "=" * 10

closure.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
def Dx(f, dx):
2+
def dfdx(x):
3+
return (f(x + dx) - f(x))/dx
4+
return dfdx
5+
6+
def f(x):
7+
return 3*x**2+x
8+
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+
"""

decorator4.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import time
2+
3+
def time_this(func):
4+
"""The time_this decorator"""
5+
6+
def decorated(*args, **kwargs):
7+
start = time.time()
8+
result = func(*args, **kwargs)
9+
print "Ran in", time.time() – start, "seconds"
10+
return result
11+
return decorated
12+
13+
# Decorator syntax
14+
@time_this
15+
def count(until):
16+
"""Counts to 'until', then returns the result"""
17+
18+
print "Counting to", until, "…"
19+
num = 0
20+
for i in xrange(to_num(until)):
21+
num += 1
22+
return num
23+
24+
def to_num(numstr):
25+
"""Turns a comma-separated number string to an int"""
26+
return int(numstr.replace(",", ""))
27+
28+
# Run count with various values
29+
for number in ("10,000", "100,000", "1,000,000"):
30+
print count(number)
31+
print "-" * 20

decorators.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
def notify(f):
2+
def g(self, n):
3+
print n
4+
return f(self, n)
5+
return g
6+
7+
class Point(object):
8+
def __init__(self, x, y):
9+
self.x = x
10+
self.y = y
11+
12+
@notify
13+
def scale(self, n):
14+
self.x = n * self.x
15+
self.y = n * self.y
16+
17+
p = Point(2.0, 3.0)
18+
p.scale(2.5)

factory4.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#coding: UTF8
2+
3+
class JapaneseGetter:
4+
"""A simple localizer a la gettext"""
5+
6+
def __init__(self):
7+
self.trans = dict(dog="犬", cat="猫")
8+
9+
def get(self, msgid):
10+
"""We'll punt if we don't have a translation"""
11+
12+
try:
13+
return unicode(self.trans[msgid], "utf-8")
14+
except KeyError:
15+
return unicode(msgid)
16+
17+
class EnglishGetter:
18+
"""Simply echoes the msg ids"""
19+
def get(self, msgid):
20+
return unicode(msgid)
21+
22+
def get_localizer(language="English"):
23+
"""The factory method"""
24+
25+
languages = dict(English=EnglishGetter,
26+
Japanese=JapaneseGetter)
27+
28+
return languages[language]()
29+
30+
# Create our localizers
31+
e, j = get_localizer("English"), get_localizer("Japanese")
32+
33+
# Localize some text
34+
for msgid in "dog parrot cat".split():
35+
print e.get(msgid), j.get(msgid)

factorymethod.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class A(object):
2+
def __init__(self):
3+
self.a = "Hello"
4+
5+
class B(object):
6+
def __init__(self):
7+
self.a = " World"
8+
myfactory = {
9+
"greeting" : A,
10+
"subject" : B,
11+
}
12+
13+
>>> print myfactory["greeting"]().a
14+
Hello
15+

flyweight.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
Flyweight Design Pattern
3+
Desc: Sharing the shareable data between the common classes and thus reducing the memory usage
4+
Code: Believing that every person in a family will have same genetic structure, we will create a code to learn about
5+
genetics of each family. If a same member of a family is given, no new object is created. (You can also create new
6+
objects unlike here but keep a reference of the heavy weighted one in the new |||r object).
7+
"""
8+
9+
class ComplexGenetics(object):
10+
""" returns a huge genetic pattern"""
11+
def __init__(self):
12+
pass
13+
14+
def genes(self, gene_code):
15+
return "ComplexPatter[%s]TooHugeinSize" % (gene_code)
16+
17+
class Families(object):
18+
""" To learn about Family Genetic Pattern """
19+
family = {}
20+
def __new__(cls, name, family_id):
21+
""" i have to capture the details before the class is created, __init__ is pseudo constructor """
22+
try:
23+
id = cls.family[family_id]
24+
except KeyError:
25+
id = object.__new__(cls)
26+
cls.family[family_id] = id
27+
return id
28+
29+
def set_genetic_info(self, genetic_info):
30+
cg = ComplexGenetics()
31+
self.genetic_info = cg.genes(genetic_info)
32+
33+
def get_genetic_info(self):
34+
return (self.genetic_info)
35+
36+
def test():
37+
# name, family_id and genetic code details (i dont care if genetic code detail varies in same family [it is research fault :-D ])
38+
data = (('a', 1, 'ATAG'), ('a', 2, 'AAGT'), ('b', 1, 'ATAG'))
39+
family_objects = []
40+
for i in data:
41+
obj = Families(i[0], i[1])
42+
obj.set_genetic_info(i[2])
43+
family_objects.append(obj)
44+
45+
for i in family_objects:
46+
print "id = " + str(id(i))
47+
print i.get_genetic_info()
48+
print "similar id's says that they are same objects "
49+
50+
if __name__ == '__main__':
51+
test()

iterator4.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""Implementation of the iterator pattern with a generator"""
2+
3+
def count_to(count):
4+
"""Counts by word numbers, up to a maximum of five"""
5+
6+
numbers = ["one", "two", "three", "four", "five"]
7+
# The zip keeps from counting over the limit
8+
for number, pos in zip(numbers, range(count)):
9+
yield number
10+
11+
# Test the generator
12+
count_to_two = lambda : count_to(2)
13+
count_to_five = lambda : count_to(5)
14+
15+
print "Counting to two…"
16+
for number in count_to_two():
17+
print number,
18+
print "\n"
19+
print "Counting to five…"
20+
for number in count_to_five():
21+
print number,

observer3.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Point(object):
2+
def __init__(self, x, y):
3+
self.x = x
4+
self.y = y
5+
6+
def scale(self, n):
7+
self.x = n * self.x
8+
self.y = n * self.y
9+
10+
def notify(f):
11+
def g(self, n):
12+
print n
13+
return f(self, n)
14+
return g
15+
16+
Point.scale = notify(Point.scale)
17+
p = Point(2.0, 3.0)
18+
p.scale(2.5)

state4.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
"""Implementation of the state pattern"""
2+
3+
class State(object):
4+
"""Base state. This is to share functionality"""
5+
6+
def scan(self):
7+
"""Scan the dial to the next station"""
8+
self.pos += 1
9+
if self.pos == len(self.stations):
10+
self.pos = 0
11+
print "Scanning… Station is", self.stations[self.pos], self.name
12+
13+
class AmState(State):
14+
def __init__(self, radio):
15+
self.radio = radio
16+
self.stations = ["1250", "1380", "1510"]
17+
self.pos = 0
18+
self.name = "AM"
19+
20+
def toggle_amfm(self):
21+
print "Switching to FM"
22+
self.radio.state = self.radio.fmstate
23+
24+
class FmState(State):
25+
def __init__(self, radio):
26+
self.radio = radio
27+
self.stations = ["81.3", "89.1", "103.9"]
28+
self.pos = 0
29+
self.name = "FM"
30+
31+
def toggle_amfm(self):
32+
print "Switching to AM"
33+
self.radio.state = self.radio.amstate
34+
35+
class Radio(object):
36+
"""A radio.
37+
It has a scan button, and an AM/FM toggle switch."""
38+
39+
def __init__(self):
40+
"""We have an AM state and an FM state"""
41+
42+
self.amstate = AmState(self)
43+
self.fmstate = FmState(self)
44+
self.state = self.amstate
45+
46+
def toggle_amfm(self):
47+
self.state.toggle_amfm()
48+
def scan(self):
49+
self.state.scan()
50+
51+
# Test our radio out
52+
radio = Radio()
53+
actions = [radio.scan] * 2 + [radio.toggle_amfm] + [radio.scan] * 2
54+
actions = actions * 2
55+
for action in actions:
56+
action()

strategy3.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
def bisection(line):
2+
return 5.5, 6.6
3+
4+
def conjugate_gradient(line):
5+
return 3.3, 4.4
6+
7+
def test():
8+
solver = conjugate_gradient
9+
print solver((5.5,5.5))
10+
solver = bisection
11+
print solver((5.5,5.5))
12+
test()
13+

testing4.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""An example of the Template pattern in Python"""
2+
3+
# Skeletons
4+
def iter_elements(getter, action):
5+
"""Template skeleton that iterates items"""
6+
7+
for element in getter():
8+
action(element)
9+
print "-" * 10
10+
11+
def rev_elements(getter, action):
12+
"""Template skeleton that iterates items in reverse order"""
13+
14+
for element in getter()[::-1]:
15+
action(element)
16+
print "-" * 10
17+
18+
# Getters
19+
def get_list():
20+
return "spam eggs".split()
21+
22+
def get_lists():
23+
return [list(x) for x in "spam eggs".split()]
24+
25+
# Actions
26+
def print_item(item):
27+
print item
28+
29+
def reverse_item(item):
30+
print item[::-1]
31+
32+
# Makes templates
33+
def make_template(skeleton, getter, action):
34+
"""Instantiate a template method with getter and action"""
35+
def template():
36+
skeleton(getter, action)
37+
return template
38+
39+
# Create our template functions
40+
templates = [make_template(s, g, a)
41+
for g in (get_list, get_lists)
42+
for a in (print_item, reverse_item)
43+
for s in (iter_elements, rev_elements)]
44+
45+
# Execute them
46+
for template in templates:
47+
template()

0 commit comments

Comments
 (0)