码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象式设计和面向函数式设计

时间:2016-05-27 14:34:25      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

面向对象式设计:

class Checker(object):
    def check(self, context):
        pass

class EmailChecker(Checker):
    def check(self, context):
        if not context[email].lower() == zanxiaofeng@163.com:
            return "Email is error"

class AccessCodeChecker(Checker):
    def check(self, context):
        if not context[access_code].lower().startswith(wg):
            return "AccessCode is error"

class ComposedChecker(Checker):
    def __init__(self, *checkers):
        self.checkers = checkers

    def check(self, context):
        for checker in self.checkers:
            result = checker.check(context)
            return result if result else None

class EmailAndAccessCodeChecker(ComposedChecker):
    def __init__(self):
        super().__init__(EmailChecker(), AccessCodeChecker())

checker = EmailAndAccessCodeChecker()
assert checker.check({email: ‘‘, access_code: wg_123}) == "Email is error"
assert checker.check({email: zanxiaofeng@163.com, access_code: wg_123}) is None

面向函数式设计:

def email_check(context):
    if not context[email].lower() == zanxiaofeng@163.com:
        return "Email is error"


def access_code_check(context):
    if not context[access_code].lower().startswith(wg):
        return "AccessCode is error"


def execute_checks(context, *checks):
    for check in checks:
        result = check(context)
        if result:
            return result


def email_and_access_code_check(context):
    return execute_checks(context, email_check, access_code_check)

assert email_and_access_code_check({email: ‘‘, access_code: wg_123}) == "Email is error"
assert email_and_access_code_check({email: zanxiaofeng@163.com, access_code: wg_123}) is None

 

  

面向对象式设计和面向函数式设计

标签:

原文地址:http://www.cnblogs.com/zanxiaofeng/p/5534239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!