Created
August 22, 2019 21:18
-
-
Save Alexei-Kornienko/9aafa845409e562949940686244bded4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
*TL;DR | |
Provides recombination business logic by chaining together using boolean logic. | |
""" | |
from abc import abstractmethod | |
class Specification(object): | |
@abstractmethod | |
def is_satisfied_by(self, candidate): | |
pass | |
class SpecificationChain(Specification): | |
def is_satisfied_by(self, candidate): | |
return True # identity comparison | |
def __and__(self, candidate): | |
return AndSpecification(self, candidate) | |
def __or__(self, candidate): | |
return OrSpecification(self, candidate) | |
def __inv__(self): | |
return NotSpecification(self) | |
class AndSpecification(SpecificationChain): | |
_one = Specification() | |
_other = Specification() | |
def __init__(self, one, other): | |
self._one = one | |
self._other = other | |
def is_satisfied_by(self, candidate): | |
return bool(self._one.is_satisfied_by(candidate) and self._other.is_satisfied_by(candidate)) | |
class OrSpecification(SpecificationChain): | |
_one = Specification() | |
_other = Specification() | |
def __init__(self, one, other): | |
self._one = one | |
self._other = other | |
def is_satisfied_by(self, candidate): | |
return bool(self._one.is_satisfied_by(candidate) or self._other.is_satisfied_by(candidate)) | |
class NotSpecification(SpecificationChain): | |
_wrapped = Specification() | |
def __init__(self, wrapped): | |
self._wrapped = wrapped | |
def is_satisfied_by(self, candidate): | |
return bool(not self._wrapped.is_satisfied_by(candidate)) | |
class User(object): | |
def __init__(self, super_user=False): | |
self.super_user = super_user | |
class UserSpecification(Specification): | |
def is_satisfied_by(self, candidate): | |
return isinstance(candidate, User) | |
class SuperUserSpecification(Specification): | |
def is_satisfied_by(self, candidate): | |
return getattr(candidate, 'super_user', False) | |
def main(): | |
print('Specification') | |
andrey = User() | |
ivan = User(super_user=True) | |
vasiliy = 'not User instance' | |
root_specification = SpecificationChain() & UserSpecification() & SuperUserSpecification() | |
print(root_specification.is_satisfied_by(andrey)) | |
print(root_specification.is_satisfied_by(ivan)) | |
print(root_specification.is_satisfied_by(vasiliy)) | |
if __name__ == '__main__': | |
main() | |
OUTPUT = """ | |
Specification | |
False | |
True | |
False | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment