Skip to content

Commit bc65ce4

Browse files
committed
Added new files.
1 parent 486fd7d commit bc65ce4

38 files changed

+2016
-0
lines changed

abstractfactory.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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")

adapter.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Barfooer:
2+
def barfoo(self, bar, foo):
3+
pass
4+
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)
11+
12+
foobarer = FoobaringWrapper(barfooer)
13+
14+
# Per-classs by subclassing and self-delegation
15+
class Foobarer(Barfooer):
16+
def foobar(self,foo, bar):
17+
return self.barfoo(bar, foo)
18+
19+
foobarer = Foobarer(some, init, params)
20+

adapter2.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Adaptee:
2+
def specific_request(self):
3+
return 'Adaptee'
4+
5+
class Adapter:
6+
def __init__(self, adaptee):
7+
self.adaptee = adaptee
8+
9+
def request(self):
10+
return self.adaptee.specific_request()
11+
12+
client = Adapter(Adaptee())
13+
print client.request()

adaptermartelli.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class UppercasingFile:
2+
def __init__(self, *a, **k):
3+
self.f = file(*a, **k)
4+
5+
def write(self, data):
6+
self.f.write(data.upper())
7+
8+
def __getattr__(self, name):
9+
return getattr(self.f, name)

bridge.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class AbstractParser:
2+
def __init__(self, scanner):
3+
self.scanner = scanner
4+
5+
class ExprParser(AbstractParser):
6+
def expr(self):
7+
t = self.scanner.next()...
8+
self.scanner.push_back(t)...
9+

bridge2.py

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

chainofresp2.py

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

command.py

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# -*- coding: utf8 -*-
2+
3+
from sys import stdout as console
4+
5+
# Обработка команды exit
6+
class SessionClosed(Exception):
7+
def __init__(self, value):
8+
self.value = value
9+
10+
# Интерфейс команды
11+
class Command:
12+
def execute(self):
13+
raise NotImplementedError()
14+
15+
def cancel(self):
16+
raise NotImplementedError()
17+
18+
def name():
19+
raise NotImplementedError()
20+
21+
# Команда rm
22+
class RmCommand(Command):
23+
def execute(self):
24+
console.write("You are executed \"rm\" command\n")
25+
26+
def cancel(self):
27+
console.write("You are canceled \"rm\" command\n")
28+
29+
def name(self):
30+
return "rm"
31+
32+
# Команда uptime
33+
class UptimeCommand(Command):
34+
def execute(self):
35+
console.write("You are executed \"uptime\" command\n")
36+
37+
def cancel(self):
38+
console.write("You are canceled \"uptime\" command\n")
39+
40+
def name(self):
41+
return "uptime"
42+
43+
# Команда undo
44+
class UndoCommand(Command):
45+
def execute(self):
46+
try:
47+
cmd = HISTORY.pop()
48+
TRASH.append(cmd)
49+
console.write("Undo command \"{0}\"\n".format(cmd.name()))
50+
cmd.cancel()
51+
52+
except IndexError:
53+
console.write("ERROR: HISTORY is empty\n")
54+
55+
def name(self):
56+
return "undo"
57+
58+
# Команда redo
59+
class RedoCommand(Command):
60+
def execute(self):
61+
try:
62+
cmd = TRASH.pop()
63+
HISTORY.append(cmd)
64+
console.write("Redo command \"{0}\"\n".format(cmd.name()))
65+
cmd.execute()
66+
67+
except IndexError:
68+
console.write("ERROR: TRASH is empty\n")
69+
def name(self):
70+
return "redo"
71+
72+
# Команда history
73+
class HistoryCommand(Command):
74+
def execute(self):
75+
i = 0
76+
for cmd in HISTORY:
77+
console.write("{0}: {1}\n".format(i, cmd.name()))
78+
i = i + 1
79+
def name(self):
80+
print "history"
81+
82+
# Команда exit
83+
class ExitCommand(Command):
84+
def execute(self):
85+
raise SessionClosed("Good bay!")
86+
87+
def name(self):
88+
return "exit"
89+
90+
# Словарь доступных команд
91+
COMMANDS = {'rm': RmCommand(), 'uptime': UptimeCommand(), 'undo': UndoCommand(), 'redo': RedoCommand(), 'history': HistoryCommand(), 'exit': ExitCommand()}
92+
93+
HISTORY = list()
94+
TRASH = list()
95+
96+
# Шелл
97+
def main():
98+
99+
try:
100+
while True:
101+
console.flush()
102+
console.write("pysh >> ")
103+
104+
cmd = raw_input()
105+
106+
try:
107+
108+
command = COMMANDS[cmd]
109+
command.execute()
110+
111+
if not isinstance(command, UndoCommand) and not isinstance(command, RedoCommand) and not isinstance(command, HistoryCommand):
112+
TRASH = list()
113+
HISTORY.append(command)
114+
115+
except KeyError:
116+
console.write("ERROR: Command \"%s\" not found\n" % cmd)
117+
118+
except SessionClosed as e:
119+
console.write(e.value)
120+
121+
if __name__ == "__main__": main()

composite2.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Component(object):
2+
def __init__(self, *args, **kw):
3+
pass
4+
5+
def component_function(self): pass
6+
7+
class Leaf(Component):
8+
def __init__(self, *args, **kw):
9+
Component.__init__(self, *args, **kw)
10+
11+
def component_function(self):
12+
print "some function"
13+
14+
class Composite(Component):
15+
def __init__(self, *args, **kw):
16+
Component.__init__(self, *args, **kw)
17+
self.children = []
18+
19+
def append_child(self, child):
20+
self.children.append(child)
21+
22+
def remove_child(self, child):
23+
self.children.remove(child)
24+
25+
def component_function(self):
26+
map(lambda x: x.component_function(), self.children)
27+
28+
c = Composite()
29+
l = Leaf()
30+
l_two = Leaf()
31+
c.append_child(l)
32+
c.append_child(l_two)
33+
c.component_function()

compositechain.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
>>> class DevelopmentPerformanceMonitor():
2+
... def getPerformanceMonitorHandlers():
3+
... return []
4+
...
5+
>>> class ProductionPerformanceMonitor():
6+
... def getPerformanceMonitorHandlers():
7+
... return [check_cpu_under_load, check_available_hd]
8+
...
9+
>>> class DevelopmentExceptionMonitor():
10+
... def getExceptionHandlers():
11+
... return [email_local_root, log_exception]
12+
...
13+
>>> class ProductionExceptionMonitor():
14+
... def getExceptionHandlers():
15+
... return [emails_system_admin, log_exception, create_ticket]
16+
...
17+
>>> class SomeSystem:
18+
... pm = None # Performance Monitor
19+
... em = None # Exception Monitor
20+
... def __init__(self, performance_monitor, exception_monitor):
21+
... pm = performance_monitor
22+
... em = exception_monitor
23+
... def on_exception(e):
24+
... for handler in em.getExceptionHandlers():
25+
... handler(e)
26+
... def perform_performance_monitoring(s):
27+
... for handler in pm.getPerformanceMonitorHandlers():
28+
... handler(s)

0 commit comments

Comments
 (0)