【发布时间】:2021-12-01 04:25:13
【问题描述】:
Insomanyarticleson Java's builder design pattern,实现如下:
public class YourModel {
// your fields here
private final long id;
//...
private YourModel(YourModelBuilder builder) {
// set everything from the builder
}
public static class YourModelBuilder {
// same fields from the model it is trying to build
private final long id;
//...
public YourModelBuilder(long id/* , .... */) {
// the normal construction pattern here...
this.id = id;
//...
}
// some builder methods for setting individual fields while allowing for chaining
public YourModel build() {
YourModel model = new YourModel(this);
// do validation here
return model;
}
}
}
或类似的东西。
这种设计模式的实现似乎满足了我的用例,以一种易于理解的方式为我的 Katalon Studio 测试手动快速轻松地创建模型,但它似乎最终可能成为维护的噩梦,特别是考虑到创建这些模型的 AUT 是不断变化的。
我们如何抽象出从模型复制到模型构建器的字段声明?
【问题讨论】:
-
Lombok 的
@Builder可能会有所帮助:projectlombok.org/features/Builder。 -
这可能正是我要找的!这是否需要我更改 POJO 模型的任何现有实现?