Skip to content

Instantly share code, notes, and snippets.

@Nilzor
Created June 28, 2012 15:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nilzor/3012094 to your computer and use it in GitHub Desktop.
Save Nilzor/3012094 to your computer and use it in GitHub Desktop.
Generic Factory Example
using System;
using System.Collections.Generic;
namespace GenericFactoryPatternExample
{
public class MainClass
{
// Example of using a service locator to get the correct factory for
// a given object type.
public static void Main()
{
var factoryA = ServiceLocator.GetFactoryFor<AlphaClass>();
var alphaObject = factoryA.Create(); // object is now strong typed
System.Diagnostics.Debug.WriteLine("Description: " + alphaObject.Description);
var factoryB = ServiceLocator.GetFactoryFor<BravoClass>();
var bravoObject = factoryB.Create();
System.Diagnostics.Debug.WriteLine("Name: " + bravoObject.Name);
}
}
public class ServiceLocator
{
public static FactoryBase<T> GetFactoryFor<T>() // The "Service Locator" method
{
if (typeof(T) == typeof(AlphaClass)) return (FactoryBase<T>)((object)new AlphaFactory());
if (typeof(T) == typeof(BravoClass)) return (FactoryBase<T>)((object)new BravoFactory());
throw new ArgumentException("No factory defined for type " + typeof(T));
}
}
public class FactoryBase<T>
{
internal virtual T Create() { return default(T); }
}
class AlphaFactory : FactoryBase<AlphaClass>
{
internal override AlphaClass Create()
{
return new AlphaClass { Description = "Hello world" };
}
}
class BravoFactory : FactoryBase<BravoClass>
{
internal override BravoClass Create()
{
return new BravoClass { Name = "Check this out" };
}
}
class AlphaClass
{
internal string Description { get; set; }
}
class BravoClass
{
internal string Name { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment