gpt4 book ai didi

java - 这是构建器模式的有效变体吗?

转载 作者:搜寻专家 更新时间:2023-11-01 03:35:20 27 4
gpt4 key购买 nike

<分区>

假设我们在它们自己的包中有 UserUserBuilder 类,我们希望在初始化之前是不可变的并且处于一致的状态,定义如下:

public class User {

private final String firstName, lastName;
private final int age;
private final String adress;
protected User(UserBuilder buildUser) { //constructor acessible only in same packge
this.firstName = buildUser.lastName;
this.lastName = buildUser.lastName;
this.age = buildUser.age;
this.adress = buildUser.adress;
}

public String getFirstName() {
return firstName;
}
... // and other getters
}

构建器类如下:

public class UserBuilder {

public final String firstName;
public final String lastName;
public int age;
public String adress;

public UserBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

public UserBuilder setAge(int age) {
this.age = age;
return this;
}

public UserBuilder setAdress(String adress) {
this.adress = adress;
return this;
}

public UserBuilder getUser() {
return this;
}

public User build() {
return new User(getUser());
}
}

最后我们在另一个包中的类中构建用户:

  public static void main(String[] args) {
User user = new UserBuilder("John","Doe")
.setAge(22)
.build();
// User user = new User(UserBuilder) //error protected constructor
}

这被认为是安全和好的设计吗?如果不是,为什么?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com