使用生成器的 C# 构造对象
Fluent 构建器是一种众所周知的构建具有许多属性的对象的模式:
Team team = teamBuilder.CreateTeam("Chelsea")
.WithNickName("The blues")
.WithShirtColor(Color.Blue)
.FromTown("London")
.PlayingAt("Stamford Bridge");
但是,由于一个特定的原因,使用它对我来说似乎不太清楚:
- 每个
Team
对象都有其最小操作状态,换句话说,必须设置的属性集(强制),以便对象可以使用。
现在,考虑到必须维持这种状态,应该如何使用 Fluent builder
方法?
With_XYZ
成员是否应该修改对象的一部分,而不会影响此状态?
也许这种情况有一些通用规则?
更新:
如果CreateTeam
方法应将强制属性作为参数,那么接下来会发生什么?
如果我(例如)省略
WithNickName
调用,会发生什么?这是否意味着昵称应该默认为某个
DefaultNickname
?这是否意味着该示例(请参阅链接)很糟糕,因为该对象可能处于无效状态?
而且,我怀疑在这种情况下,流畅的构建方法实际上失去了它的“美感”,不是吗?
Fluent builder is a well-known pattern to build objects with many properties:
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.
Now, how should the Fluent builder
approach be used considering that you have to maintain this state?
Should the With_XYZ
members modify the part of the object, that can't affect this state?
Maybe there are some general rules for this situation?
Update:
If the CreateTeam
method should take the mandatory properties as arguments, what happens next?
What happens if I (for example) omit the
WithNickName
call?Does this mean that the nickname should be defaulted to some
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CreateTeam()
应该将强制属性作为参数。CreateTeam()
should have the mandatory the properties as parameters.在我看来,Fluent Interface 的要点是:
Seems to me the points of Fluent Interface are: