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

Posted 昝昝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象式设计和面向函数式设计相关的知识,希望对你有一定的参考价值。

面向对象式设计:

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

class EmailChecker(Checker):
    def check(self, context):
        if not context[email].lower() == [email protected]:
            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: [email protected], access_code: wg_123}) is None

面向函数式设计:

def email_check(context):
    if not context[email].lower() == [email protected]:
        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: [email protected], access_code: wg_123}) is None

 

  

以上是关于面向对象式设计和面向函数式设计的主要内容,如果未能解决你的问题,请参考以下文章

函数式编程让你忘记设计模式

函数式编程让你忘记设计模式

《架构之美》阅读笔记06

告别相杀!面向对象和函数式编程共存

8/14 - 函数式编程离我们有多远?

里式替换原则——面向对象程序设计原则