Views: 7.9K
Replies: 1
Archived
|
Need working code for Abstract Factory and Factory Method Pattern with genericsHi All,
I would like to get both Abstract Factory and Factory Method patterns written with generics. I look forward to some wonderful 'code blocks'. Thanks Volkan Genç, Jul 30, 2011
|
|
Reply 1I have implemented both patterns with generics, based on the examples provided on the dofactory site (structural example for Abstract Factory and real-world example for Factory Method).
Abstract Factory: public class ConcreteFactory<AClass, BClass> : AbstractFactory where AClass : AbstractProductA, new() where BClass : AbstractProductB, new() { public override AbstractProductA CreateProductA() { return new AClass(); } public override AbstractProductB CreateProductB() { return new BClass(); } } public class ConcreteFactory1 : ConcreteFactory<ProductA1, ProductB1> { } public class ConcreteFactory2 : ConcreteFactory<ProductA2, ProductB2> { } Factory Method: public class ConcreteDocument<TClass, UClass, VClass> : Document where TClass : Page, new() where UClass : Page, new() where VClass : Page, new() { public override void CreatePages() { Pages.Add(new TClass()); Pages.Add(new UClass()); Pages.Add(new VClass()); } } public class ConcreteDocument<TClass, UClass, VClass, WClass, XClass> : Document where TClass : Page, new() where UClass : Page, new() where VClass : Page, new() where WClass : Page, new() where XClass : Page, new() { public override void CreatePages() { Pages.Add(new TClass()); Pages.Add(new UClass()); Pages.Add(new VClass()); Pages.Add(new WClass()); Pages.Add(new XClass()); } } public class Resume : ConcreteDocument<SkillsPage, EducationPage, ExperiencePage> { } public class Report : ConcreteDocument<IntroductionPage, ResultsPage, ConclusionPage, SummaryPage, BibliographyPage> { } The Abstract Factory surely gains from the generics, because the implementation is reusable in all cases. If these code blocks look like the gofactory .NET Optimized versions, it is without intent because I haven't yet had the chance to look at those. Hopefully this is what you were looking for. Mathieu Lavigne, Aug 01, 2011
|