Skip to content

Commit cf65942

Browse files
committed
Merge pull request #1 from faif/master
up
2 parents 480905b + ca277dd commit cf65942

29 files changed

+1201
-170
lines changed

3-tier.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ def __get__(self, obj, klas):
1919
class BusinessLogic(object):
2020
""" Business logic holding data store instances """
2121

22-
data = Data()
22+
def __init__(self, data):
23+
self.data = data
2324

2425
def product_list(self):
2526
return self.data['products'].keys()
@@ -31,8 +32,8 @@ def product_information(self, product):
3132
class Ui(object):
3233
""" UI interaction class """
3334

34-
def __init__(self):
35-
self.business_logic = BusinessLogic()
35+
def __init__(self, logic):
36+
self.business_logic = logic
3637

3738
def get_product_list(self):
3839
print('PRODUCT LIST:')
@@ -53,7 +54,9 @@ def get_product_information(self, product):
5354

5455

5556
def main():
56-
ui = Ui()
57+
data = Data()
58+
logic = BusinessLogic(data)
59+
ui = Ui(logic)
5760
ui.get_product_list()
5861
ui.get_product_information('cheese')
5962
ui.get_product_information('eggs')
@@ -69,7 +72,7 @@ def main():
6972
# cheese
7073
# eggs
7174
# milk
72-
#
75+
#
7376
# (Fetching from Data Store)
7477
# PRODUCT INFORMATION:
7578
# Name: Cheese, Price: 2.00, Quantity: 10

README.md

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,36 +9,55 @@ comments at the bottom up to date.
99

1010
Current Patterns:
1111

12+
__Creational Patterns__:
13+
1214
| Pattern | Description |
1315
|:-------:| ----------- |
14-
| [3-tier](3-tier.py) | data<->business logic<->presentation separation (strict relationships) |
1516
| [abstract_factory](abstract_factory.py) | use a generic function with specific factories |
16-
| [adapter](adapter.py) | adapt one interface to another using a whitelist |
1717
| [borg](borg.py) | a singleton with shared-state among instances |
18+
| [builder](builder.py) | instead of using multiple constructors, builder object receives parameters and returns constructed objects |
19+
| [factory_method](factory_method.py) | delegate a specialized function/method to create instances |
20+
| [lazy_evaluation](lazy_evaluation.py) | lazily-evaluated property pattern in Python |
21+
| [pool](pool.py) | preinstantiate and maintain a group of instances of the same type |
22+
| [prototype](prototype.py) | use a factory and clones of a prototype for new instances (if instantiation is expensive) |
23+
24+
__Structural Patterns__:
25+
26+
| Pattern | Description |
27+
|:-------:| ----------- |
28+
| [3-tier](3-tier.py) | data<->business logic<->presentation separation (strict relationships) |
29+
| [adapter](adapter.py) | adapt one interface to another using a white-list |
1830
| [bridge](bridge.py) | a client-provider middleman to soften interface changes |
19-
| [builder](builder.py) | call many little discrete methods rather than having a huge number of constructor parameters |
20-
| [catalog](catalog.py) | general methods will call different specialized methods based on construction parameter |
21-
| [chain](chain.py) | apply a chain of successive handlers to try and process the data |
22-
| [chaining_method](chaining_method.py) | continue callback next object method |
23-
| [command](command.py) | bundle a command and arguments to call later |
2431
| [composite](composite.py) | encapsulate and provide access to a number of different objects |
2532
| [decorator](decorator.py) | wrap functionality with other functionality in order to affect outputs |
2633
| [facade](facade.py) | use one class as an API to a number of others |
27-
| [factory_method](factory_method.py) | delegate a specialized function/method to create instances |
28-
| [front_controller](front_controller.py) | single handler requests coming to the application |
2934
| [flyweight](flyweight.py) | transparently reuse existing instances of objects with similar/identical state |
30-
| [graph_search](graph_search.py) | (graphing algorithms, not design patterns) |
31-
| [lazy_evaluation](lazy_evaluation.py) | lazily-evaluated property pattern in Python |
35+
| [front_controller](front_controller.py) | single handler requests coming to the application |
36+
| [mvc](mvc.py) | model<->view<->controller (non-strict relationships) |
37+
| [proxy](proxy.py) | an object funnels operations to something else |
38+
39+
__Behavioral Patterns__:
40+
41+
| Pattern | Description |
42+
|:-------:| ----------- |
43+
| [chain](chain.py) | apply a chain of successive handlers to try and process the data |
44+
| [catalog](catalog.py) | general methods will call different specialized methods based on construction parameter |
45+
| [chaining_method](chaining_method.py) | continue callback next object method |
46+
| [command](command.py) | bundle a command and arguments to call later |
3247
| [mediator](mediator.py) | an object that knows how to connect other objects and act as a proxy |
3348
| [memento](memento.py) | generate an opaque token that can be used to go back to a previous state |
34-
| [mvc](mvc.py) | model<->view<->controller (non-strict relationships) |
3549
| [observer](observer.py) | provide a callback for notification of events/changes to data |
36-
| [pool](pool.py) | preinstantiate and maintain a group of instances of the same type |
37-
| [prototype](prototype.py) | use a factory and clones of a prototype for new instances (if instantiation is expensive) |
38-
| [proxy](proxy.py) | an object funnels operations to something else |
3950
| [publish_subscribe](publish_subscribe.py) | a source syndicates events/data to 0+ registered listeners |
51+
| [registry](registry.py) | keep track of all subclasses of a given class |
4052
| [specification](specification.py) | business rules can be recombined by chaining the business rules together using boolean logic |
41-
| [state](state.py) | logic is org'd into a discrete number of potential states and the next state that can be transitioned to |
53+
| [state](state.py) | logic is organized into a discrete number of potential states and the next state that can be transitioned to |
4254
| [strategy](strategy.py) | selectable operations over the same data |
4355
| [template](template.py) | an object imposes a structure but takes pluggable components |
4456
| [visitor](visitor.py) | invoke a callback for all items of a collection |
57+
58+
59+
__Others__:
60+
61+
| Pattern | Description |
62+
|:-------:| ----------- |
63+
| [graph_search](graph_search.py) | (graphing algorithms, not design patterns) |

__init__.py

Whitespace-only changes.

adapter.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,9 @@ class Adapter(object):
4545
4646
>>> objects = []
4747
>>> dog = Dog()
48+
>>> print(dog.__dict__)
4849
>>> objects.append(Adapter(dog, make_noise=dog.bark))
50+
>>> print(objects[0].original_dict())
4951
>>> cat = Cat()
5052
>>> objects.append(Adapter(cat, make_noise=cat.meow))
5153
>>> human = Human()
@@ -70,12 +72,18 @@ def __init__(self, obj, **adapted_methods):
7072
def __getattr__(self, attr):
7173
"""All non-adapted calls are passed to the object"""
7274
return getattr(self.obj, attr)
73-
75+
76+
def original_dict(self):
77+
"""Print original object dict"""
78+
return self.obj.__dict__
7479

7580
def main():
7681
objects = []
7782
dog = Dog()
83+
print(dog.__dict__)
7884
objects.append(Adapter(dog, make_noise=dog.bark))
85+
print(objects[0].__dict__)
86+
print(objects[0].original_dict())
7987
cat = Cat()
8088
objects.append(Adapter(cat, make_noise=cat.meow))
8189
human = Human()
@@ -91,6 +99,9 @@ def main():
9199
main()
92100

93101
### OUTPUT ###
102+
# {'name': 'Dog'}
103+
# {'make_noise': <bound method Dog.bark of <__main__.Dog object at 0x7f631ba3fb00>>, 'obj': <__main__.Dog object at 0x7f631ba3fb00>}
104+
# {'name': 'Dog'}
94105
# A Dog goes woof!
95106
# A Cat goes meow!
96107
# A Human goes 'hello'

builder.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ def __init__(self):
3131
def new_building(self):
3232
self.building = Building()
3333

34+
def build_floor(self):
35+
raise NotImplementedError
36+
37+
def build_size(self):
38+
raise NotImplementedError
3439

3540
# Concrete Builder
3641
class BuilderHouse(Builder):

catalog.py

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,108 @@ def main_method(self):
4646
self._static_method_choices[self.param]()
4747

4848

49+
# Alternative implementation for different levels of methods
50+
class CatalogInstance:
51+
52+
"""
53+
catalog of multiple methods that are executed depending on an init
54+
parameter
55+
"""
56+
57+
def __init__(self, param):
58+
self.x1 = 'x1'
59+
self.x2 = 'x2'
60+
# simple test to validate param value
61+
if param in self._instance_method_choices:
62+
self.param = param
63+
else:
64+
raise ValueError("Invalid Value for Param: {0}".format(param))
65+
66+
def _instance_method_1(self):
67+
print("Value {}".format(self.x1))
68+
69+
def _instance_method_2(self):
70+
print("Value {}".format(self.x2))
71+
72+
_instance_method_choices = {'param_value_1': _instance_method_1,
73+
'param_value_2': _instance_method_2}
74+
75+
76+
def main_method(self):
77+
"""
78+
will execute either _instance_method_1 or _instance_method_2
79+
depending on self.param value
80+
"""
81+
self._instance_method_choices[self.param].__get__(self)()
82+
83+
84+
class CatalogClass:
85+
86+
"""
87+
catalog of multiple class methods that are executed depending on an init
88+
parameter
89+
"""
90+
91+
x1 = 'x1'
92+
x2 = 'x2'
93+
94+
def __init__(self, param):
95+
# simple test to validate param value
96+
if param in self._class_method_choices:
97+
self.param = param
98+
else:
99+
raise ValueError("Invalid Value for Param: {0}".format(param))
100+
101+
@classmethod
102+
def _class_method_1(cls):
103+
print("Value {}".format(cls.x1))
104+
105+
@classmethod
106+
def _class_method_2(cls):
107+
print("Value {}".format(cls.x2))
108+
109+
_class_method_choices = {'param_value_1': _class_method_1,
110+
'param_value_2': _class_method_2}
111+
112+
def main_method(self):
113+
"""
114+
will execute either _class_method_1 or _class_method_2
115+
depending on self.param value
116+
"""
117+
self._class_method_choices[self.param].__get__(None, self.__class__)()
118+
119+
120+
class CatalogStatic:
121+
122+
"""
123+
catalog of multiple static methods that are executed depending on an init
124+
parameter
125+
"""
126+
def __init__(self, param):
127+
# simple test to validate param value
128+
if param in self._static_method_choices:
129+
self.param = param
130+
else:
131+
raise ValueError("Invalid Value for Param: {0}".format(param))
132+
133+
@staticmethod
134+
def _static_method_1():
135+
print("executed method 1!")
136+
137+
@staticmethod
138+
def _static_method_2():
139+
print("executed method 2!")
140+
141+
_static_method_choices = {'param_value_1': _static_method_1,
142+
'param_value_2': _static_method_2}
143+
144+
def main_method(self):
145+
"""
146+
will execute either _static_method_1 or _static_method_2
147+
depending on self.param value
148+
"""
149+
self._static_method_choices[self.param].__get__(None, self.__class__)()
150+
49151
def main():
50152
"""
51153
>>> c = Catalog('param_value_1').main_method()
@@ -57,8 +159,20 @@ def main():
57159
test = Catalog('param_value_2')
58160
test.main_method()
59161

162+
test = CatalogInstance('param_value_1')
163+
test.main_method()
164+
165+
test = CatalogClass('param_value_2')
166+
test.main_method()
167+
168+
test = CatalogStatic('param_value_1')
169+
test.main_method()
170+
60171
if __name__ == "__main__":
61172
main()
62173

63174
### OUTPUT ###
64175
# executed method 2!
176+
# Value x1
177+
# Value x2
178+
# executed method 1!

0 commit comments

Comments
 (0)