Search code examples
c#oopdesign-patternsfactory-pattern

Examples of the use for the factory design pattern in C#


I understand the theory behind the factory design pattern now, but can't seem to find any realistic examples of it's use. Can someone be as kind enough as to provide one?


Solution

  • There are a few variants of factory designs: abstract factory, factory method, etc... Since you're interested in a real-world example, I thought I'd share what I did.

    As one example, I used a data access factory to return a concrete instance of a data access class. The logic class doesn't know or care which database is being used; it simply asks the factory for a data class, and then uses that data class.

    This is the method within my DataAccessFactory class. It is responsible for determing which data class to use, and returning it to the caller:

    public static T GetDataInterface<T>() where T : class
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
    
        T theObject = (from t in assembly.GetTypes()
                       where t.GetInterfaces().Contains(typeof(T))
                         && t.GetConstructor(Type.EmptyTypes) != null
                         && t.Namespace == _namespace
                       select Activator.CreateInstance(t) as T).FirstOrDefault() as T;
    
        return theObject as T;
    }
    

    And this is how one of my business logic classes makes a DAL request:

    return DataAccessFactory.GetDataInterface<IApplicationData>().GetAll();
    

    The business logic is completely decoupled from the data access layer. Hope that helps.