PortabilityFactory.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. namespace MatrixIO.IO
  5. {
  6. public abstract class PortabilityFactory
  7. {
  8. private static PortabilityFactory _current;
  9. public static PortabilityFactory Current
  10. {
  11. get
  12. {
  13. if (_current == null) throw new InvalidOperationException();
  14. return _current;
  15. }
  16. }
  17. protected PortabilityFactory()
  18. {
  19. if (_current != null) throw new InvalidOperationException("You can only create one instance of the Portability Factory.");
  20. Debug.WriteLine("Setting PortabilityFactory.Current");
  21. _current = this;
  22. }
  23. public virtual IList<T> CreateList<T>()
  24. {
  25. return new List<T>();
  26. }
  27. public virtual IList<T> CreateList<T>(int capacity)
  28. {
  29. return new List<T>(capacity);
  30. }
  31. public virtual IList<T> CreateList<T>(IEnumerable<T> collection)
  32. {
  33. return new List<T>(collection);
  34. }
  35. public virtual void TraceWriteLine(object value, string category = null)
  36. {
  37. Debug.WriteLine(new String(' ', _traceIndentLevel * 2) + (category == null ? value : category + ": " + value));
  38. }
  39. public virtual void TraceAssert(bool condition, string message = null)
  40. {
  41. Debug.Assert(condition, message);
  42. }
  43. public virtual void DispatchAction(Action action)
  44. {
  45. action.Invoke();
  46. }
  47. private int _traceIndentLevel = 0;
  48. public virtual int TraceIndentLevel
  49. {
  50. get
  51. {
  52. return _traceIndentLevel;
  53. }
  54. set
  55. {
  56. _traceIndentLevel = value;
  57. }
  58. }
  59. }
  60. public static class Portability
  61. {
  62. public static IList<T> CreateList<T>()
  63. {
  64. return PortabilityFactory.Current != null ? PortabilityFactory.Current.CreateList<T>() : new List<T>();
  65. }
  66. public static IList<T> CreateList<T>(int capacity)
  67. {
  68. return PortabilityFactory.Current != null ? PortabilityFactory.Current.CreateList<T>(capacity) : new List<T>(capacity);
  69. }
  70. public static IList<T> CreateList<T>(IEnumerable<T> collection)
  71. {
  72. return PortabilityFactory.Current != null ? PortabilityFactory.Current.CreateList<T>(collection) : new List<T>(collection);
  73. }
  74. public static void DispatchAction(Action action)
  75. {
  76. if (PortabilityFactory.Current != null) PortabilityFactory.Current.DispatchAction(action);
  77. else action.Invoke();
  78. }
  79. }
  80. }