I want to develop a Factory of INotifications.

public interface INotification
    string Text { get; }
    string UserId { get; }
    NotificationType NotificationType { get; }

The problem is, that the NotificationFactory has to be ready for getting multiple types of inputs , why? because there are multiple implementations of INotification, and the factory should be able to return instance of each of them depending the request.

INotification not1= NotificationFactory.GetNotification<EmailNotification>(new Email("hi there"));
INotification not1= NotificationFactory.GetNotification<PackageNotification>(new Package("10$","book"));
INotification not2= NotificationFactory.GetNotification<XXXTypeNotification>(new XXXX);

As you see, it would have different types in the input parameters.(they are know at design time) I would not like to create a method for each type of notification the factory is enabled to create... Ho can i design that Factory? It does not need to use generics , the code I attached is just for understanding the problem.

Many thanks!!

  • Variadic variants (params) ? Docs: docs.microsoft.com/en-us/dotnet/csharp/language-reference/… Note that, when this route is taken, the code editor auto-complete doesn't work anymore. This may make it harder to use overall, as users have to remember each argument needed by each function (type of notification). A different approach would be to create wrappers for each type (i.e. your existing classes Email, Package), and then implement a GetNotification method that accepts an instance of any of these classes, and convert them into a notification object.
    – rwong
    May 26, 2018 at 12:08
  • Another approach is to write extension methods - attach them (i.e. make subject) to the the Email and Package class; name the method GetNotification, and take an extra input parameter of type NotificationFactory. This requires flipping the subject-object.
    – rwong
    May 26, 2018 at 12:10
  • It is probably necessary to write multiple methods anyway, because at the minimum, the compiler needs to know that the method (overloaded, i.e. one or more implementations) return type T1B when given type T1A; return type T2B when given type T2A; and so on. The C# type system doesn't do that.
    – rwong
    May 26, 2018 at 12:12
  • Extension methods can improve their specificity (i.e. making them less easily triggered for the wrong inputs) by having their subjects implement interfaces (tag interfaces) exclusively for this purpose (of improving the specificity of extension methods)
    – rwong
    May 26, 2018 at 12:14
  • The params approach is not good enough because as you say , it is hard to don't have runtime errors..
    – X.Otano
    May 26, 2018 at 12:34


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.