Factory Method Template Using Generics-C #

I’m just learning Generics.When I have an abstract method template, for example:

//Abstract Product interface IPage { string pageType(); } //Concerete Product 1 class ResumePage : IPage { public string pageType() { return "Resume Page"; } } //Concrete Product 2 class SummaryPage : IPage { public string pageType() { return "SummaryPage"; } } //Fcatory Creator class FactoryCreator { public IPage CreateOnRequirement(int i) { if (i == 1) return new ResumePage(); else { return new SummaryPage(); } } } //Client/Consumer void Main() { FactoryCreator c = new FactoryCreator(); IPage p; p = c.CreateOnRequirement(1); Console.WriteLine("Page Type is {0}", p.pageType()); p = c.CreateOnRequirement(2); Console.WriteLine("Page Type is {0}", p.pageType()); Console.ReadLine(); } 

how to convert code using generics?

+4
source share
1 answer

You can implement a method with a common signature, and then create a type passed to the type parameter.

However, you must specify the new() condition.
This means that it will only accept types that have an empty constructor.

Like this:

 public IPage CreateOnRequirement<TCreationType>() where TCreationType:IPage,new() { return new TCreationType(); } 
+6
source

Source: https://habr.com/ru/post/1304867/


All Articles