vendredi 6 octobre 2023

Pattern for doing a different thing based on which subclass is received?

Currently I have something similar to the following data classes and I want the receiver of CreateScheduledEventRequest to perform different actions when ScheduleInfo is a RepeatingTask versus when it is a OneShotTask:

public record CreateScheduledEventRequest
{
    public ScheduleInfo ScheduleInfo = new OneShotTask();
}

public abstract record ScheduleInfo;

public record RepeatingTask : ScheduleInfo
{
    public TimeSpan RepeatEvery;
}

public record OneShotTask : ScheduleInfo
{
    public DateTimeOffset RunAt;
}

As an exercise in OOP-design I would also like to implement this without introspecting which subclass I have received. I tried naively to just create overloaded methods for each subclass, but I didn't manage to please the type-checker when calling them with the base class.

I'm hoping there is a way for me to write one method that takes a RepeatingTask, and another that takes a OneShotTask, and then somehow using C# language features dispatch to the correct implementation. I suspect maybe a strategy pattern can be used, but I'm worried that is a bit heavy for this little thing.

Aucun commentaire:

Enregistrer un commentaire