简体   繁体   中英

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:

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 . 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 .

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. It totally contradicts with Open Closed principle of Uncle Bob, since if there is gonna be additional case, then the method must be modified. Absolutely unacceptable.

Python doesn't have function overloading. What it does have is first-class function objects.

Create a dict that maps Receiver values to the appropriate function.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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