Created
June 28, 2012 15:45
-
-
Save Nilzor/3012094 to your computer and use it in GitHub Desktop.
Generic Factory Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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