forked from faif/python-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspecification.py
More file actions
Latest commit
117 lines (76 loc) · 2.71 KB
/
Copy pathspecification.py
File metadata and controls
117 lines (76 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Gordeev Andrey <gordeev.and.and@gmail.com>
Specification provide recombination business logic by
chaining together using boolean logic
"""
fromabcimportabstractmethod
classSpecification(object):
defand_specification(self, candidate):
raiseNotImplementedError()
defor_specification(self, candidate):
raiseNotImplementedError()
defnot_specification(self):
raiseNotImplementedError()
@abstractmethod
defis_satisfied_by(self, candidate):
pass
classCompositeSpecification(Specification):
@abstractmethod
defis_satisfied_by(self, candidate):
pass
defand_specification(self, candidate):
returnAndSpecification(self, candidate)
defor_specification(self, candidate):
returnOrSpecification(self, candidate)
defnot_specification(self):
returnNotSpecification(self)
classAndSpecification(CompositeSpecification):
_one=Specification()
_other=Specification()
def__init__(self, one, other):
self._one=one
self._other=other
defis_satisfied_by(self, candidate):
returnbool(self._one.is_satisfied_by(candidate) and
self._other.is_satisfied_by(candidate))
classOrSpecification(CompositeSpecification):
_one=Specification()
_other=Specification()
def__init__(self, one, other):
self._one=one
self._other=other
defis_satisfied_by(self, candidate):
returnbool(self._one.is_satisfied_by(candidate) or
self._other.is_satisfied_by(candidate))
classNotSpecification(CompositeSpecification):
_wrapped=Specification()
def__init__(self, wrapped):
self._wrapped=wrapped
defis_satisfied_by(self, candidate):
returnbool(notself._wrapped.is_satisfied_by(candidate))
classUser(object):
def__init__(self, super_user=False):
self.super_user=super_user
classUserSpecification(CompositeSpecification):
defis_satisfied_by(self, candidate):
returnisinstance(candidate, User)
classSuperUserSpecification(CompositeSpecification):
defis_satisfied_by(self, candidate):
returngetattr(candidate, 'super_user', False)
if__name__=='__main__':
print('Specification')
andrey=User()
ivan=User(super_user=True)
vasiliy='not User instance'
root_specification=UserSpecification().\
and_specification(SuperUserSpecification())
print(root_specification.is_satisfied_by(andrey))
print(root_specification.is_satisfied_by(ivan))
print(root_specification.is_satisfied_by(vasiliy))
### OUTPUT ###
# Specification
# False
# True
# False