在构建器设计模式中,使用“构建器”内部类,通过它我们可以设置该类的字段值。定义这个类的目的是什么?
使用构建器模式的主要原因之一是它解决了伸缩构造函数问题
如果是这样,为什么我们不能直接使用 setter 方法呢?
(注意:虽然有些问题已经讨论过这个主题( link ),但这些问题和答案并不是很直接。因此,我必须起草这个问题)
例如, 为什么要这样做?
public class Employee {
private int id;
private String name;
public Employee (Builder builder) {
this.id = builder.id;
this.name = builder.name;
}
public static class Builder {
private int id;
private String name;
public Builder id(int id) {
this.id = id;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Employee build() {
return new Employee(this);
}
}
}
// Employee emp = new Employee.Builder().id(1).name("Abc").build();
而不是这个?
public class Employee {
private int id;
private String name;
public Employee id(int id) {
this.id = id;
return this;
}
public Employee name(String name) {
this.name = name;
return this;
}
}
// Employee emp = new Employee().id(1).name("Abc");
最佳答案
"... What is the purpose of defining this class? ..."
这个想法是将字段访问器与构建器设计分开。
一种常见的误解是,访问器是专门为从类外部访问字段而创建的。
它们实际上只是面向对象设计原则的一部分;作为定义数据的单点分配和检索的方式。
换句话说,setter 和 getter 应该在整个类中使用。
class Employee {
int id;
String name;
public Employee(int id, String name) {
setId(id);
setName(name);
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
相反,
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
考虑到这一点,您会希望有一个内部类来分离设计。
但请记住,设计模式只是轮廓。没有确切的方法来编写它们;因为它们只是建议。
如果通过删除内部类来调整模式可以改进您的设计,我建议使用它。
有时设计概念可能会发生冲突,实际上会降低产品的可扩展性,从而违背其使用目的。
关于java - 为什么我们在Builder设计模式中需要 'Builder class'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76609185/