简体   繁体   English

重载和策略模式

[英]Overloading and strategy pattern

I'm trying to write an email delivery system.我正在尝试编写一个电子邮件传递系统。 I have this enum, for all users, users that were logged in the last 3 months and 6 months:对于所有用户,我有这个枚举,在过去 3 个月和 6 个月内登录的用户:

class Receiver(enum.Enum):
    ALL = "ALL"
    THREE_MONTHS = "THREE_MONTHS"
    SIX_MONTHS = "SIX_MONTHS"

The problem is, I'm trying to implement a Strategy pattern , so I need to enforce type checking .问题是,我正在尝试实现Strategy 模式,所以我需要强制执行类型检查 I know it is impossible by default, but ... any idea would be appreciated.我知道默认情况下这是不可能的,但是......任何想法都会受到赞赏。

I need it to look like:我需要它看起来像:

def send_to(Receiver.ALL):
    pass

def send_to(Receiver.THREE_MONTHS):
    pass

def send_to(Receiver.SIX_MONTHS):
    pass

Yeah, I have Java background .是的,我有Java背景

And the general sender would pass the value accordingly :并且一般发件人会相应地传递值:

@api_view(["POST"])
def send_email(request):
        email_to = request.data["emailTo"]
        send_to(email_to)

Note: I do not want to write multiple if checks or switch cases.注意:我不想编写多个 if 检查或 switch case。 It totally contradicts with Open Closed principle of Uncle Bob, since if there is gonna be additional case, then the method must be modified.这完全违背了 Bob 大叔的 Open Closed 原则,因为如果有额外的情况,则必须修改方法。 Absolutely unacceptable.绝对不能接受。

Python doesn't have function overloading. Python没有函数重载。 What it does have is first-class function objects.它所拥有的是一流的函数对象。

Create a dict that maps Receiver values to the appropriate function.创建一个将Receiver值映射到适当函数的dict

def send_to_all():
    pass

def send_to_last_three_months():
    pass

def send_to_last_six_months():
    pass

senders = {
    Receiver.ALL: send_to_all,
    Receiver.THREE_MONTHS: send_to_last_three_months,
    Receiver.SIX_MONTHS: send_to_last_six_months,
}

@api_view(["POST"])
def send_email(request):
    email_to = request.data["emailTo"]
    sender = senders[email_to]
    sender()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM