Menu
CoddyTech

Recap: Dispatch by Behavior

Lesson 42 of 48 in Coddy's Python for C# Developers course.

challenge icon

Challenge

Beginner

Implement Email.send(text) returning email: plus text and Sms.send(text) returning sms: plus text. Implement Dispatcher(channels) storing a shallow copy of the list and dispatch(text) returning one result per channel in original order. The driver reads email/sms/log tokens and a message, supplies its own log object, creates the dispatcher, then clears the original list before dispatching. Repeats remain repeats. It prints results or none for no channels. All methods format strings only; no messages are actually sent.

C# transfer checkpoint

Like a List<T> copy constructor, a Python shallow copy isolates outer-list edits while retaining the channel objects.

C# reference excerpt: executable statements assume using System; type-only excerpts illustrate the declared contract.

var channels = new System.Collections.Generic.List<string> { "email" };
var stored = new System.Collections.Generic.List<string>(channels);
channels.Clear();
Console.WriteLine(stored.Count);

Python pattern

channels = ["email"]
stored = channels.copy()
channels.clear()
print(len(stored))

Editable implementation files: email.py, sms.py, dispatcher.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation modules.

Try it yourself

from email import Email
from sms import Sms
from dispatcher import Dispatcher

class Log:
    def send(self, text):
        return "log:" + text

factories = {"email": Email, "sms": Sms, "log": Log}
channels = [factories[name]() for name in input().split()]
text = input()
dispatcher = Dispatcher(channels)
channels.clear()
results = dispatcher.dispatch(text)
if not results:
    print("none")
for result in results:
    print(result)

All lessons in Python for C# Developers

Practice on your own: Online Python compiler