java 如何改进构建器模式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1638722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to improve the builder pattern?
提问by tangens
Motivation
动机
Recently I searched for a way to initialize a complex object without passing a lot of parameter to the constructor. I tried it with the builder pattern, but I don't like the fact, that I'm not able to check at compile time if I really set all needed values.
最近我在寻找一种方法来初始化一个复杂的对象,而无需向构造函数传递大量参数。我用构建器模式尝试过它,但我不喜欢这样一个事实,即我无法在编译时检查我是否真的设置了所有需要的值。
Traditional builder pattern
传统建造者模式
When I use the builder pattern to create my Complexobject, the creation is more "typesafe", because it's easier to see what an argument is used for:
当我使用构建器模式创建我的Complex对象时,创建更“类型安全”,因为更容易看到参数的用途:
new ComplexBuilder()
.setFirst( "first" )
.setSecond( "second" )
.setThird( "third" )
...
.build();
But now I have the problem, that I can easily miss an important parameter. I can check for it inside the build()method, but that is only at runtime. At compile time there is nothing that warns me, if I missed something.
但是现在我遇到了问题,我很容易错过一个重要的参数。我可以在build()方法中检查它,但这只是在运行时。在编译时,如果我错过了什么,没有任何警告我。
Enhanced builder pattern
增强型构建器模式
Now my idea was to create a builder, that "reminds" me if I missed a needed parameter. My first try looks like this:
现在我的想法是创建一个构建器,如果我错过了一个需要的参数,它会“提醒”我。我的第一次尝试是这样的:
public class Complex {
private String m_first;
private String m_second;
private String m_third;
private Complex() {}
public static class ComplexBuilder {
private Complex m_complex;
public ComplexBuilder() {
m_complex = new Complex();
}
public Builder2 setFirst( String first ) {
m_complex.m_first = first;
return new Builder2();
}
public class Builder2 {
private Builder2() {}
Builder3 setSecond( String second ) {
m_complex.m_second = second;
return new Builder3();
}
}
public class Builder3 {
private Builder3() {}
Builder4 setThird( String third ) {
m_complex.m_third = third;
return new Builder4();
}
}
public class Builder4 {
private Builder4() {}
Complex build() {
return m_complex;
}
}
}
}
As you can see, each setter of the builder class returns a different internal builder class. Each internal builder class provides exactly one setter method and the last one provides only a build() method.
如您所见,构建器类的每个 setter 都返回一个不同的内部构建器类。每个内部构建器类只提供一个 setter 方法,最后一个只提供一个 build() 方法。
Now the construction of an object again looks like this:
现在对象的构造再次如下所示:
new ComplexBuilder()
.setFirst( "first" )
.setSecond( "second" )
.setThird( "third" )
.build();
...but there is no way to forget a needed parameter. The compiler wouldn't accept it.
...但没有办法忘记所需的参数。编译器不会接受它。
Optional parameters
可选参数
If I had optional parameters, I would use the last internal builder class Builder4to set them like a "traditional" builder does, returning itself.
如果我有可选参数,我将使用最后一个内部构建器类Builder4来设置它们,就像“传统”构建器所做的那样,返回自身。
Questions
问题
- Is this a well known pattern? Does it have a special name?
- Do you see any pitfalls?
- Do you have any ideas to improve the implementation - in the sense of fewer lines of code?
- 这是众所周知的模式吗?它有什么特别的名字吗?
- 你看到任何陷阱吗?
- 您是否有任何改进实现的想法 - 在更少的代码行的意义上?
采纳答案by Esko
No, it's not new. What you're actually doing there is creating a sort of a DSLby extending the standard builder pattern to support branches which is among other things an excellent way to make sure the builder doesn't produce a set of conflicting settings to the actual object.
不,这不是新的。您实际上在做的是通过扩展标准构建器模式来支持分支来创建一种DSL,这是确保构建器不会为实际对象生成一组冲突设置的绝佳方式。
Personally I think this is a great extension to builder pattern and you can do all sorts of interesting things with it, for example at work we have DSL builders for some of our data integrity tests which allow us to do things like assertMachine().usesElectricity().and().makesGrindingNoises().whenTurnedOn();. OK, maybe not the best possible example but I think you get the point.
我个人认为这是对构建器模式的一个很好的扩展,你可以用它做各种有趣的事情,例如在工作中,我们有 DSL 构建器用于我们的一些数据完整性测试,它允许我们执行诸如assertMachine().usesElectricity().and().makesGrindingNoises().whenTurnedOn();. 好吧,也许不是最好的例子,但我认为你明白了。
回答by Michael Borgwardt
The traditional builder pattern already handles this: simply take the mandatory parameters in the constructor. Of course, nothing prevents a caller from passing null, but neither does your method.
传统的构建器模式已经解决了这个问题:只需在构造函数中获取强制参数。当然,没有什么可以阻止调用者传递 null,但您的方法也不会。
The big problem I see with your method is that you either have a combinatorical explosion of classes with the number of mandatory parameters, or force the user to set the parameters in one particular sqeuence, which is annoying.
我在你的方法中看到的一个大问题是,你要么有一个具有强制性参数数量的类的组合爆炸,要么强迫用户在一个特定的序列中设置参数,这很烦人。
Also, it is a lot of additional work.
此外,还有很多额外的工作。
回答by clinux
public class Complex {
private final String first;
private final String second;
private final String third;
public static class False {}
public static class True {}
public static class Builder<Has1,Has2,Has3> {
private String first;
private String second;
private String third;
private Builder() {}
public static Builder<False,False,False> create() {
return new Builder<>();
}
public Builder<True,Has2,Has3> setFirst(String first) {
this.first = first;
return (Builder<True,Has2,Has3>)this;
}
public Builder<Has1,True,Has3> setSecond(String second) {
this.second = second;
return (Builder<Has1,True,Has3>)this;
}
public Builder<Has1,Has2,True> setThird(String third) {
this.third = third;
return (Builder<Has1,Has2,True>)this;
}
}
public Complex(Builder<True,True,True> builder) {
first = builder.first;
second = builder.second;
third = builder.third;
}
public static void test() {
// Compile Error!
Complex c1 = new Complex(Complex.Builder.create().setFirst("1").setSecond("2"));
// Compile Error!
Complex c2 = new Complex(Complex.Builder.create().setFirst("1").setThird("3"));
// Works!, all params supplied.
Complex c3 = new Complex(Complex.Builder.create().setFirst("1").setSecond("2").setThird("3"));
}
}
回答by Martin
Why don't you put "needed" parameters in the builders constructor?
为什么不在构建器构造函数中放置“需要”的参数?
public class Complex
{
....
public static class ComplexBuilder
{
// Required parameters
private final int required;
// Optional parameters
private int optional = 0;
public ComplexBuilder( int required )
{
this.required = required;
}
public Builder setOptional(int optional)
{
this.optional = optional;
}
}
...
}
This pattern is outlined in Effective Java.
这种模式在Effective Java 中有概述。
回答by Sled
Instead of using multiple classes I would just use one class and multiple interfaces. It enforces your syntax without requiring as much typing. It also allows you to see all related code close together which makes it easier to understand what is going on with your code at a larger level.
我不会使用多个类,而是只使用一个类和多个接口。它强制执行您的语法,而无需太多输入。它还允许您将所有相关代码紧密地放在一起,从而更容易在更大的层面上理解您的代码发生了什么。
回答by reccles
I've seen/used this:
我见过/使用过这个:
new ComplexBuilder(requiredvarA, requiedVarB).optional(foo).optional(bar).build();
Then pass these to your object that requires them.
然后将这些传递给需要它们的对象。
回答by JRL
IMHO, this seems bloated. If you haveto have all the parameters, pass them in the constructor.
恕我直言,这似乎臃肿。如果您必须拥有所有参数,请将它们传递到构造函数中。
回答by Eva
The Builder Pattern is generally used when you have a lot of optional parameters. If you find you need many required parameters, consider these options first:
当您有很多可选参数时,通常会使用构建器模式。如果您发现需要许多必需的参数,请首先考虑以下选项:
- Your class might be doing too much. Double check that it doesn't violate Single Responsibility Principle. Ask yourself why you need a class with so many required instance variables.
- You constructor might be doing too much. The job of a constructor is to construct. (They didn't get very creative when they named it ;D ) Just like classes, methods have a Single Responsibility Principle. If your constructor is doing more than just field assignment, you need a good reason to justify that. You might find you need a Factory Methodrather than a Builder.
- Your parameters might be doing too little. Ask yourself if your parameters can be grouped into a small struct (or struct-like object in the case of Java). Don't be afraid to make small classes. If you do find you need to make a struct or small class, don't forget torefactoroutfunctionalitythat belongs in the struct rather than your larger class.
回答by Aaron
回答by brariden
Question 1: Regarding the name of the pattern, I like the name "Step Builder":
问题1:关于模式的名称,我喜欢“Step Builder”这个名字:
- http://rdafbn.blogspot.com/2012/07/step-builder-pattern_28.html
- http://www.javacodegeeks.com/2013/05/building-smart-builders.html
- http://rdafbn.blogspot.com/2012/07/step-builder-pattern_28.html
- http://www.javacodegeeks.com/2013/05/building-smart-builders.html
Question 2/3: Regarding pitfalls and recommendations, this feels over complicated for most situations.
问题 2/3:关于陷阱和建议,这在大多数情况下感觉过于复杂。
You are enforcing a sequencein how you use your builder which is unusual in my experience. I could see how this would be important in some cases but I've never needed it. For example, I don't see the need to force a sequence here:
Person.builder().firstName("John").lastName("Doe").build()Person.builder().lastName("Doe").firstName("John").build()However, many times the builder needed to enforce some constraints to prevent bogus objects from being built. Maybe you want to ensure that all required fields are provided or that combinations of fields are valid. I'm guessing this is the real reason you want to introduce sequencing into the building.
In this case, I like recommendation of Joshua Bloch to do the validation in the build() method. This helps with cross field validation because everything is available at this point. See this answer: https://softwareengineering.stackexchange.com/a/241320
您正在强制使用构建器的顺序,这在我的经验中是不寻常的。我可以看出这在某些情况下有多重要,但我从来不需要它。例如,我认为没有必要在此处强制执行序列:
Person.builder().firstName("John").lastName("Doe").build()Person.builder().lastName("Doe").firstName("John").build()但是,很多时候构建器需要强制执行一些约束以防止构建虚假对象。也许您想确保提供所有必填字段或字段组合有效。我猜这就是您想在建筑物中引入排序的真正原因。
在这种情况下,我喜欢 Joshua Bloch 的建议在 build() 方法中进行验证。这有助于跨领域验证,因为此时一切都可用。看到这个答案:https: //softwareengineering.stackexchange.com/a/241320
In summary, I wouldn't add any complication to the code just because you are worried about "missing" a call to a builder method. In practice, this is easily caught with a test case. Maybe start with a vanilla Builder and then introduce this if you keep getting bitten by missing method calls.
总之,我不会仅仅因为您担心“错过”对构建器方法的调用而给代码添加任何复杂性。在实践中,这很容易被测试用例捕获。也许从一个普通的 Builder 开始,然后如果你一直被丢失的方法调用所困扰,那么引入它。

