简体   繁体   English

带构建器的C#构造对象

[英]C# construction objects with builder

Fluent builder is a well-known pattern to build objects with many properties: Fluent构建器是一种众所周知的模式,用于构建具有许多属性的对象:

Team team = teamBuilder.CreateTeam("Chelsea")
    .WithNickName("The blues")
    .WithShirtColor(Color.Blue)
    .FromTown("London")
    .PlayingAt("Stamford Bridge");

However, using it doesn't seem very clear to me due to one particular reason: 但是,由于一个特殊原因,使用它对我来说似乎不太清楚:

  • Every Team object has its minimal operational state , in other words, set of properties which have to be set (mandatory), so that the object is ready to use. 每个Team对象都有其最小的操作状态 ,换句话说,必须设置的属性集(必需),以便对象可以使用。

Now, how should the Fluent builder approach be used considering that you have to maintain this state? 现在,考虑到你必须保持这种状态,应如何使用Fluent builder方法?

Should the With_XYZ members modify the part of the object, that can't affect this state? 如果With_XYZ成员修改了对象的一部分,那么这不会影响这种状态吗?

Maybe there are some general rules for this situation? 也许这种情况有一些一般规则?


Update: 更新:

If the CreateTeam method should take the mandatory properties as arguments, what happens next? 如果CreateTeam方法应该将强制属性作为参数,接下来会发生什么?

  • What happens if I (for example) omit the WithNickName call? 如果我(例如)省略WithNickName调用会发生什么?

  • Does this mean that the nickname should be defaulted to some DefaultNickname ? 这是否意味着昵称应该默认为某个DefaultNickname

  • Does this mean that the example (see the link) is bad, because the object can be left in invalid state? 这是否意味着该示例(请参阅链接)不好,因为该对象可能处于无效状态?

  • And, well, I suspect that in this case the fluent building approach actually loses it's "beauty", doesn't it? 而且,我怀疑在这种情况下,流畅的建筑方法实际上失去了它的“美丽”,不是吗?

CreateTeam() should have the mandatory the properties as parameters. CreateTeam()应该具有必需的属性作为参数。

Team CreateTeam(string name, Color shirtColor, string Town)
{
}

Seems to me the points of Fluent Interface are: 在我看来,Fluent Interface的要点是:

  • Minimize the number of parameters to zero in a constructor while still dynamically initializing certain properties upon creation. 在构造函数中将参数数量最小化为零,同时在创建时仍动态初始化某些属性。
  • Makes the property/ parameter-value association very clear - in a large parameter list, what value is for what? 使属性/参数值关联非常清晰 - 在大型参数列表中,什么值是什么? Can't tell without digging further. 没有进一步挖掘就说不出来。
  • The coding style of the instantiation is very clean, readable, and editable . 实例化的编码风格非常干净,可读和可编辑 Adding or deleting property settings with this formatting style is less error prone. 使用此格式设置样式添加或删除属性设置不易出错。 IE delete an entire line, rather than edit in the middle of a long parameter list; IE删除整行,而不是在长参数列表的中间编辑; not to mention editing the wrong parameter 更不用说编辑错误的参数了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM