Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Base
- {
- public int Id { get; set; }
- }
- public class A : BaseClass
- {
- public int ValueA { get; set; }
- }
- public class B : BaseClass
- {
- public int ValueB { get; set; }
- }
- public class CreateRequest
- {
- public int Id { get; set; }
- public int Value { get; set; } // default 0 for Base, value for A / B
- public int Type { get; set; } // 0 - for Base, 1 for A, 2 for B
- }
- public abstract class BaseFactoryAbstr // sorry, it sounds better in real code
- {
- protected abstract Base Create();
- protected abstract Fill(Base base, CreateRequest createRequest);
- public Base CreateAndFill(CreateRequest createRequest)
- {
- var base = Create();
- Fill(base, createRequest);
- return base;
- }
- }
- public class BaseFactory
- {
- protected virtual Base Create()
- {
- return new Base();
- }
- protected virtual void Fill(Base base, CreateRequest createRequest)
- {
- base.Id = createRequest.Id;
- }
- }
- public class AFactory : BaseFactory
- {
- protected override Base Create()
- {
- return new A();
- }
- protected override void Fill(Base base, CreateRequest createRequest)
- {
- base.Fill(base, createRequest);
- var a = base as A;
- if (a == null)
- throw new InvalidOperationException("...");
- a.ValueA = createRequest.Value;
- }
- }
- public class BFactory : BaseFactory
- {
- protected override Base Create()
- {
- return new B();
- }
- protected override void Fill(Base base, CreateRequest createRequest)
- {
- base.Fill(base, createRequest);
- var b = base as B;
- if (b == null)
- throw new InvalidOperationException("...");
- b.ValueB = createRequest.Value;
- }
- }
- public void Create(CreateRequest request)
- {
- BaseFactory factory;
- switch (request.Type)
- {
- case 0:
- factory = new BaseFactory();
- break;
- case 1:
- factory = new AFactory();
- break;
- case 2:
- factory = new BFactory();
- break;
- default:
- throw new InvalidOperationException("...");
- }
- Base base = factory.CreateAndFill(request);
- }
- public abstract class BaseFactoryAbstr<T> // sorry, it sounds better in real code
- where T : Base, new()
- {
- protected T Create()
- {
- return new T();
- }
- // ...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement