How to design an immutable object with complex initialization

后端 未结 6 1153
北恋
北恋 2021-02-02 15:59

I\'m learning about DDD, and have come across the statement that \"value-objects\" should be immutable. I understand that this means that the objects state should not change aft

6条回答
  •  不思量自难忘°
    2021-02-02 16:34

    Use a builder:

    public class Entity
    {
       public class Builder
       {
         private int _field1;
         private int _field2;
         private int _field3;
    
         public Builder WithField1(int value) { _field1 = value; return this; }
         public Builder WithField2(int value) { _field2 = value; return this; }
         public Builder WithField3(int value) { _field3 = value; return this; }
    
         public Entity Build() { return new Entity(_field1, _field2, _field3); }
       }
    
       private int _field1;
       private int _field2;
       private int _field3;
    
       private Entity(int field1, int field2, int field3) 
       {
         // Set the fields.
       }
    
       public int Field1 { get { return _field1; } }
       public int Field2 { get { return _field2; } }
       public int Field3 { get { return _field3; } }
    
       public static Builder Build() { return new Builder(); }
    }
    

    Then create it like:

    Entity myEntity = Entity.Build()
                       .WithField1(123)
                       .WithField2(456)
                       .WithField3(789)
                      .Build()
    

    If some of the parameters are optional you won't need to call the WithXXX method and they can have default values.

提交回复
热议问题