[英]Builder class for generic type list
I have a class which have a generic type list, I want to set this field using builder pattern, please help me, I am not able to find any suitable content in the internet我有一个具有通用类型列表的 class,我想使用构建器模式设置此字段,请帮助我,我无法在互联网上找到任何合适的内容
Java Class Java Class
public class DialogCar<T> implements Parcelable {
private String type;
private List<T> selectedValues;
...
please let me know the Builder class for the above java class请让我知道上述 java class 的 Builder class
You could parameterize the builder as well:您也可以参数化构建器:
class DialogCarBuilder<T> {
private String type;
private List<T> selectedValues;
public DialogCarBuilder<T> withType(String type) {
this.type = type;
return this;
}
public DialogCarBuilder<T> withSelectedValues(List<T> selectedValues) {
this.selectedValues = selectedValues;
return this;
}
public DialogCar<T> build() {
return new DialogCar<>(type, selectedValues);
}
}
Then use it:然后使用它:
DialogCarBuilder<Integer> b1 = new DialogCarBuilder<Integer>();
b1.withSelectedValues(... <HERE PASS LIST OF INTEGERS>).build();
Not doing your homework for you, but hints to get you going:不是为您做功课,而是提示您前进:
The purpose of a builder pattern is to be able to have multiple calls to collect the data required for the new object before creating it.构建器模式的目的是能够在创建新 object 之前进行多次调用以收集所需的数据。
So your builder should have a addSelectedValue(T value)
" method that simply takes a T
value, and adds it to a builder-internal List<T> values
list. And then, the your build()
method simply passes on that list for example.因此,您的构建器应该有一个
addSelectedValue(T value)
" 方法,该方法只需要一个T
值,并将其添加到构建器内部的List<T> values
列表中。然后,您的build()
方法只需将该列表传递给例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.