Skip to content

Commit 6993592

Browse files
committed
Merge pull request faif#89 from Ketouem/registry-pattern
Implementing registry pattern
2 parents 480905b + 3f19ca8 commit 6993592

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ Current Patterns:
3737
|[prototype](prototype.py)| use a factory and clones of a prototype for new instances (if instantiation is expensive) |
3838
|[proxy](proxy.py)| an object funnels operations to something else |
3939
|[publish_subscribe](publish_subscribe.py)| a source syndicates events/data to 0+ registered listeners |
40+
|[registry](registry.py)| keeping track of all subclasses of a given class |
4041
|[specification](specification.py)| business rules can be recombined by chaining the business rules together using boolean logic |
4142
|[state](state.py)| logic is org'd into a discrete number of potential states and the next state that can be transitioned to |
4243
|[strategy](strategy.py)| selectable operations over the same data |

‎registry.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
5+
classRegistryHolder(type):
6+
7+
REGISTRY={}
8+
9+
def__new__(cls, name, bases, attrs):
10+
new_cls=type.__new__(cls, name, bases, attrs)
11+
"""
12+
Here the name of the class is used as key but it could be any class
13+
parameter.
14+
"""
15+
cls.REGISTRY[new_cls.__name__] =new_cls
16+
returnnew_cls
17+
18+
@classmethod
19+
defget_registry(cls):
20+
returndict(cls.REGISTRY)
21+
22+
23+
classBaseRegisteredClass(metaclass=RegistryHolder):
24+
"""
25+
Any class that will inherits from BaseRegisteredClass will be included
26+
inside the dict RegistryHolder.REGISTRY, the key being the name of the
27+
class and the associated value, the class itself.
28+
"""
29+
pass
30+
31+
if__name__=="__main__":
32+
print("Before subclassing: ")
33+
forkinRegistryHolder.REGISTRY:
34+
print(k)
35+
36+
classClassRegistree(BaseRegisteredClass):
37+
38+
def__init__(self, *args, **kwargs):
39+
pass
40+
print("After subclassing: ")
41+
forkinRegistryHolder.REGISTRY:
42+
print(k)
43+
44+
### OUTPUT ###
45+
# Before subclassing:
46+
# BaseRegisteredClass
47+
# After subclassing:
48+
# BaseRegisteredClass
49+
# ClassRegistree

0 commit comments

Comments
(0)