Tuesday, November 9, 2010

Abstract Factory pattern in simple terms

Just tried out abstract factory pattern... One of my colleague had issues coming up with the pattern.. Just helped him with the sample below;

Invocation point:
var obj = FactoryManager.GetFactory(1);

Implementation:

namespace ConsoleApplication2
{
    internal class RootDO
    {

    }

    internal sealed class SubDO1 : RootDO
    {

    }

    internal sealed class SubDO2 : RootDO
    {

    }

    internal abstract class RootClass<T> where T: RootDO ,new ()
    {

    }

    internal sealed class SubClass1<T> : RootClass<T> where T: RootDO,new ()
    {

    }

    internal sealed class SubClass2<T> : RootClass<T> where T: RootDO, new ()
    {

    }
    internal interface IFactory<S, T>
    {
         S GetObject();
    }

    internal class SubClass1Factory : IFactory<SubClass1<SubDO1>,SubDO1>
    {
        public SubClass1<SubDO1> GetObject()
        {
            return new SubClass1<SubDO1>();
        }

        internal static SubClass1<SubDO1> GetFactory()
        {
            SubClass1Factory s = new SubClass1Factory();
            return s.GetObject();
        }
    }

    public class FactoryManager
    {
        public static object GetFactory(int type)
        {
            return SubClass1Factory.GetFactory();
        }
    }
}
 



No comments:

Post a Comment