Click here to Skip to main content
Click here to Skip to main content

Better factories in C#

, 17 Oct 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
This short article just shows the evolution of my implementation of the Factory pattern in C#.

Introduction

This short article just shows the evolution of my implementation of the Factory pattern in C#.

Since Factory pattern is so frequently used, this article describes better ways to implement it in C#.

I could go and show some UML to describe pattern but lets go straight to the code, people unfamiliar with this pattern can Google it.

Using the code

Below diagram shows example concrete class that our factory could build for us, they all implement same interface.

I am going to use an enum ConcreteType as key to map concrete types, in your implementation you can use whatever better fits you.

Factory Version 1

In this version work is done by a switch, it can be implemented even in Framework 1.0.

using System;

namespace BetterFactories
{
    /// <summary>
    /// Verbose way
    /// </summary>
    public class FactoryV1
    {
        public IMyInterface Get(ConcreteType concreteType)
        {
            switch (concreteType)
            {
                case ConcreteType.Concrete1:
                    return new MyConcreteClass1();
                case ConcreteType.Concrete2:
                    return new MyConcreteClass2();
                case ConcreteType.Concrete3:
                    return new MyConcreteClass3();
                default:
                    throw new NotImplementedException();
            }
        }
    }
}

Factory Version 2

In this version we have a Dictionary were we keep mappings for our concrete types.

Since now we are using generics we need Framework 2.0 or above.

using System;
using System.Collections.Generic;
namespace BetterFactories
{
    /// <summary>
    /// More stylish but slow and cast needed.
    /// </summary>
    public class FactoryV2
    {
        public FactoryV2()
        {
            _Mappings = new Dictionary<ConcreteType,Type>(3);
            _Mappings.Add(ConcreteType.Concrete1, typeof(MyConcreteClass1));
            _Mappings.Add(ConcreteType.Concrete2, typeof(MyConcreteClass2));
            _Mappings.Add(ConcreteType.Concrete3, typeof(MyConcreteClass3));
        }
        public IMyInterface Get(ConcreteType concreteType)
        {
            Type type;
            if(_Mappings.TryGetValue(concreteType, out type))
            {
                return Activator.CreateInstance(type) as IMyInterface;
            }
            else
                throw new NotImplementedException();
        }
        readonly Dictionary<ConcreteType, Type> _Mappings;
    }
} 

After doing a benchmark to Activator.CreateInstance class I realized there was a performance hit here.

Factory Version 3

Here we have a similar approach but now our Dictionary points to a Func<T> which improves performance and avoids casting.

Since this uses Func<T> we need Framework 3.5 or above.

using System;
using System.Collections.Generic;
namespace BetterFactories
{
    /// <summary>
    /// Best way so far to have a factory, it performs well and types are compiler checked.
    /// </summary>
    public class FactoryV3
    {
        public FactoryV3()
        {
            _Mappings = new Dictionary<ConcreteType,Func<IMyInterface>>(3);
            _Mappings.Add(ConcreteType.Concrete1, () => new MyConcreteClass1());
            _Mappings.Add(ConcreteType.Concrete2, () => new MyConcreteClass2());
            _Mappings.Add(ConcreteType.Concrete3, () => new MyConcreteClass3());
        }
        public IMyInterface Get(ConcreteType concreteType)
        {
            Func<IMyInterface> func;
            if (_Mappings.TryGetValue(concreteType, out func))
            {
                return func();
            }
            else
                throw new NotImplementedException();
        }
        readonly Dictionary<ConcreteType, Func<IMyInterface>> _Mappings;
    }
} 

Points of Interest

After years of implementing this pattern it has changed several times but these three versions encapsulate the milestones.

If you have suggestions to improve it please bring up your comments.

Project attached contains all source code created in VS2008.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

arturomonriv

Mexico Mexico
No Biography provided

Comments and Discussions

 
QuestionService Locator or Simple Dependecy Injecter PinmemberMember 189736923-Oct-13 6:15 
QuestionGreat PinmemberSamuel Langlois21-Oct-13 9:32 
AnswerRe: Great Pinmemberarturomonriv21-Oct-13 9:42 
SuggestionFactory V3 for .NET 2.0 PinmemberOlivier DALET18-Oct-13 1:35 
Questionwhy recreate the wheel? PinmemberDurrmeyer17-Oct-13 23:50 
GeneralMy vote of 5 PinprofessionalPaulo Zemek17-Oct-13 18:51 
GeneralMy vote of 2 PinmemberFlorian Rosmann16-Oct-13 21:11 
GeneralRe: My vote of 2 Pinmemberednrg18-Oct-13 6:22 
GeneralMy vote of 3 PinmemberKlaus Luedenscheidt16-Oct-13 20:48 
GeneralConsider it as V4 PinmemberWonde Tadesse16-Oct-13 19:04 
GeneralRe: Consider it as V4 PinmemberRobert Rohde17-Oct-13 3:41 
GeneralRe: Consider it as V4 Pinmemberarturomonriv17-Oct-13 4:15 
GeneralMy vote of 3 PinprofessionalPaulo Zemek16-Oct-13 18:19 
GeneralMany things to consider. PinprofessionalPaulo Zemek16-Oct-13 17:11 
GeneralRe: Many things to consider. Pinmemberarturomonriv16-Oct-13 18:06 
GeneralRe: Many things to consider. PinprofessionalPaulo Zemek16-Oct-13 18:17 
GeneralRe: Many things to consider. Pinmemberarturomonriv17-Oct-13 4:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411023.1 | Last Updated 17 Oct 2013
Article Copyright 2013 by arturomonriv
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid