Skip to content

Instantly share code, notes, and snippets.

@trbngr
Created February 10, 2014 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trbngr/8911315 to your computer and use it in GitHub Desktop.
Save trbngr/8911315 to your computer and use it in GitHub Desktop.
using System;
namespace ConsoleApplication2
{
internal class Program
{
private static void Main()
{
var bar = UniversalFactory.Create<Bar>(23);
Console.Out.WriteLine(bar);
}
public interface IFactory<out T>
{
T Create(int id);
}
private class BarFactory : IFactory<IBar>
{
public IBar Create(int id)
{
return new Bar();
}
}
private class FooFactory : IFactory<IFoo>
{
public IFoo Create(int id)
{
return new Foo();
}
}
public static class UniversalFactory
{
// New factories should be added here.
private static readonly IFactory<IFoo> FooFactoryEx;
private static readonly IFactory<IBar> BarFactoryEx;
static UniversalFactory()
{
// These bindings could also be provided via a DI framework like Ninject.
FooFactoryEx = new FooFactory();
BarFactoryEx = new BarFactory();
}
// Maps concrete objects to factories according to the interface(s) they implement.
public static TConcreteType Create<TConcreteType>(int id)
{
var concreteType = typeof(TConcreteType);
if (typeof(IFoo).IsAssignableFrom(concreteType))
return (TConcreteType) FooFactoryEx.Create(id);
if (typeof(IBar).IsAssignableFrom(concreteType))
return (TConcreteType) BarFactoryEx.Create(id);
return default(TConcreteType);
}
}
}
internal class Foo :IFoo
{
}
internal interface IFoo
{
}
interface IBar
{
}
class Bar : IBar
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment