Need working code for Abstract Factory and Factory Method Pattern with generics

 
88   96.5
Jul 30, 2011
 
Hi 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



80   96.3
Aug 01, 2011
I 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> { }
Even though both are possible, I don't think the Factory Method implementation is any better using the generics the way I've done it. (And I can't seem to find any better solution).

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.