Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. public class Base
  2. {
  3. public int Id { get; set; }
  4. }
  5.  
  6. public class A : BaseClass
  7. {
  8. public int ValueA { get; set; }
  9. }
  10.  
  11. public class B : BaseClass
  12. {
  13. public int ValueB { get; set; }
  14. }
  15.  
  16. public class CreateRequest
  17. {
  18. public int Id { get; set; }
  19. public int Value { get; set; } // default 0 for Base, value for A / B
  20. public int Type { get; set; } // 0 - for Base, 1 for A, 2 for B
  21. }
  22.  
  23. public abstract class BaseFactoryAbstr // sorry, it sounds better in real code
  24. {
  25. protected abstract Base Create();
  26.  
  27. protected abstract Fill(Base base, CreateRequest createRequest);
  28.  
  29. public Base CreateAndFill(CreateRequest createRequest)
  30. {
  31. var base = Create();
  32. Fill(base, createRequest);
  33. return base;
  34. }
  35. }
  36.  
  37. public class BaseFactory
  38. {
  39. protected virtual Base Create()
  40. {
  41. return new Base();
  42. }
  43.  
  44. protected virtual void Fill(Base base, CreateRequest createRequest)
  45. {
  46. base.Id = createRequest.Id;
  47. }
  48. }
  49.  
  50. public class AFactory : BaseFactory
  51. {
  52. protected override Base Create()
  53. {
  54. return new A();
  55. }
  56.  
  57. protected override void Fill(Base base, CreateRequest createRequest)
  58. {
  59. base.Fill(base, createRequest);
  60.  
  61. var a = base as A;
  62. if (a == null)
  63. throw new InvalidOperationException("...");
  64.  
  65. a.ValueA = createRequest.Value;
  66. }
  67. }
  68.  
  69. public class BFactory : BaseFactory
  70. {
  71. protected override Base Create()
  72. {
  73. return new B();
  74. }
  75.  
  76. protected override void Fill(Base base, CreateRequest createRequest)
  77. {
  78. base.Fill(base, createRequest);
  79.  
  80. var b = base as B;
  81. if (b == null)
  82. throw new InvalidOperationException("...");
  83.  
  84. b.ValueB = createRequest.Value;
  85. }
  86. }
  87.  
  88. public void Create(CreateRequest request)
  89. {
  90. BaseFactory factory;
  91. switch (request.Type)
  92. {
  93. case 0:
  94. factory = new BaseFactory();
  95. break;
  96. case 1:
  97. factory = new AFactory();
  98. break;
  99. case 2:
  100. factory = new BFactory();
  101. break;
  102. default:
  103. throw new InvalidOperationException("...");
  104. }
  105.  
  106. Base base = factory.CreateAndFill(request);
  107. }
  108.  
  109. public abstract class BaseFactoryAbstr<T> // sorry, it sounds better in real code
  110. where T : Base, new()
  111. {
  112. protected T Create()
  113. {
  114. return new T();
  115. }
  116. // ...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement