Created
February 10, 2014 06:31
-
-
Save trbngr/8911315 to your computer and use it in GitHub Desktop.
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; | |
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