Saturday, June 16, 2012

Factory Pattern

using System;
using System.Collections.Generic;
using System.Reflection;
using Factory2.Autos;

namespace Factory2
{
    ///

    /// A simple auto factory that creates various types of automobiles
    /// based on a key for Type lookup
    ///

    public class AutoFactory
    {
        Dictionary autos;

        public AutoFactory()
        {
            LoadTypesICanReturn();
        }

        public IAuto CreateInstance(string carName)
        {
            Type t = GetTypeToCreate(carName);

            if(t == null)
                return new NullAuto();

            return Activator.CreateInstance(t) as IAuto;
        }

        Type GetTypeToCreate(string carName)
        {
            foreach (var auto in autos)
            {
                if (auto.Key.Contains(carName))
                {
                    return autos[auto.Key];
                }
            }

            return null;
        }

        void LoadTypesICanReturn()
        {
            autos = new Dictionary();

            Type[] typesInThisAssembly = Assembly.GetExecutingAssembly().GetTypes();

            foreach (Type type in typesInThisAssembly)
            {
                if (type.GetInterface(typeof(IAuto).ToString()) != null)
                {
                    autos.Add(type.Name.ToLower(), type);
                }
            }
        }
    }
}

using Factory2.Autos;

namespace Factory2
{
    ///

    /// simple factory
    ///

    class Program
    {
        static void Main(string[] args)
        {
            string carName = args[0];

            AutoFactory factory = new AutoFactory();

            IAuto car = factory.CreateInstance(carName);

            car.TurnOn();
            car.TurnOff();
        }
    }
}


namespace Factory2.Autos
{
    public interface IAuto
    {
        void TurnOn();
        void TurnOff();
    }
}

using System;

namespace Factory2.Autos
{
    public class MiniCooper : IAuto
    {
        public void TurnOn()
        {
            Console.WriteLine("The Mini Cooper is on! 1.6 Liters of brutal force is churning.");
        }

        public void TurnOff()
        {
            Console.WriteLine("The Mini Cooper is has turned off.");
        }
    }
}

namespace Factory2.Autos
{
    public class NullAuto : IAuto
    {
        public void TurnOn()
        {
           
        }

        public void TurnOff()
        {
           
        }
    }
}

No comments: