如何设计与复杂的初始化不可变对象 [英] How to design an immutable object with complex initialization
问题描述
我了解DDD和所遇到的声明说:值对象应该是一成不变的。据我所知,这意味着它已经被创建后的对象状态应该不会改变。这是怎么样的思考我的新方式,但它是有道理的在许多情况下。
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 after it has been created. This is kind of a new way of thinking for me, but it makes sense in many cases.
好了,我开始创建不可变的值对象。
Ok, so I start creating immutable value-objects.
- 我要确保他们采取了整个状态参数的构造函数,
- 我不不要再增加属性setter,
- 并确保没有方法允许修改内容(只返回新的实例)。
但现在我想创建该值对象将包含8种不同的数值。如果我创建具有8个数字参数我觉得这不会是很容易使用,或者更确切地说,构造 - 它会很容易传入数字时犯了一个错误。这不可能是好的设计
But now I want to create this value object that will contain 8 different numeric values. If I create a constructor having 8 numeric parameters I feel that it will not be very easy to use, or rather - it will be easy to make a mistake when passing in the numbers. This can't be good design.
的所以,问题是:的有没有让我不可变对象更好的其他任何方式..,任何魔法,可以在C#来完成,以克服在构造一个长参数列表?我在听你的想法。
So the questions is: Are there any other ways of making my immutable object better.., any magic that can be done in C# to overcome a long parameter list in the constructor? I'm very interested in hearing your ideas..
更新很感兴趣:之前有人提到它,一个想法已经在这里讨论:
http://stackoverflow.com/questions/263585/immutable -object图案,在C-什么-DO-你思考
UPDATE: Before anyone mentions it, one idea has been discussed here: http://stackoverflow.com/questions/263585/immutable-object-pattern-in-c-what-do-you-think
是否有兴趣听取其他建议或意见,虽然。
Would be interested in hearing other suggestions or comments though.
推荐答案
使用一个生成器:
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()
如果某些参数都是可选的,你不会需要调用该WithXXX方法,它们可以有默认值。
If some of the parameters are optional you won't need to call the WithXXX method and they can have default values.
这篇关于如何设计与复杂的初始化不可变对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!