fork download
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class Test
  5. {
  6. public static void Main()
  7. {
  8. string s = Factory.Instance.Create<string>();
  9. Console.WriteLine(s);
  10. int i = Factory.Instance.Create<int>();
  11. Console.WriteLine(i);
  12. }
  13. }
  14.  
  15. class Factory {
  16. private readonly IDictionary<Type,Func<object>> registry = new Dictionary<Type,Func<object>>();
  17. private static Factory instance;
  18. public static Factory Instance {
  19. get {
  20. if (instance != null)
  21. return instance;
  22. var f = new Factory();
  23. f.Register<string>(() => "hello");
  24. f.Register<int>(() => 123);
  25. instance = f;
  26. return instance;
  27. }
  28. }
  29. public void Register<T>(Func<T> make) {
  30. registry.Add(typeof(T), () => (object)make());
  31. }
  32. public T Create<T>() {
  33. return (T)registry[typeof(T)]();
  34. }
  35. }
Success #stdin #stdout 0.03s 14532KB
stdin
Standard input is empty
stdout
hello
123