Skip to content

Instantly share code, notes, and snippets.

@Alexei-Kornienko
Created August 22, 2019 21:18
Show Gist options
  • Save Alexei-Kornienko/9aafa845409e562949940686244bded4 to your computer and use it in GitHub Desktop.
Save Alexei-Kornienko/9aafa845409e562949940686244bded4 to your computer and use it in GitHub Desktop.
#!/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