ポリシーパターン
Appendix-1 クラスを用いた実装例
import abc
class Rule(metaclass=abc.ABCMeta):
@abc.abstractmethod
def is_ok(self, value):
pass
class Rule001(Rule):
def is_ok(self, value):
return (value.type == 'special')
class Rule002(Rule):
def is_ok(self, value):
return (value.price == 0)
class Rule003(Rule):
def is_ok(self, value):
return (value.unit >= 10)
class Policy:
def __init__(self):
self.rules = []
def add(self, rule):
self.rules.append(rule)
def is_comply(self, value):
for rule in self.rules:
if not rule.is_ok(value):
return False
return True
if __name__=='__main__':
# 正常データ
value1 = {
type: "special",
price: 0,
unit: 10
}
p = Policy()
p.add(Rule001())
p.add(Rule002())
p.add(Rule003())
result = p.is_comply(value1)
print(result) # => True
# 異常データ
value2 = {
type: "standard",
price: 1000,
unit: 5
}
p = Policy()
p.add(Rule001())
p.add(Rule002())
p.add(Rule003())
result = p.is_comply(value2)
print(result) # => Flase
Appendix-2 関数を用いた実装例
def rule_001(value):
return (value.type == 'special')
def rule_002(value):
return (value.price == 0)
def rule_003(value):
return (value.unit >= 10)
def check_policy(value):
rules = [rule_001, rule_002, rule_003]
for rule in rules:
if not rule(value):
return Flase
return True
if __name__=='__main__':
# 正常データ
value1 = {
type: "special",
price: 0,
unit: 10
}
result = check_policy(value1)
print(result) # => True
# 異常データ
value2 = {
type: "standard",
price: 1000,
unit: 5
}
result = check_policy(value2)
print(result) # => Flase