gpt4 book ai didi

Java实现构建器模式的最佳方式

转载 作者:搜寻专家 更新时间:2023-10-30 20:00:12 27 4
gpt4 key购买 nike

以下哪项是实现构建器模式的更好方法?

1) 在构建器中使用对象而不是它的所有属性来构建(并在构建器构造函数中创建它):

public class Person {
private String firstName;
// other properties ...

private Person() {}

// getters ...

public static class Builder {
// person object instead of all the person properties
private Person person;

public Builder() {
person = new Person();
}

public Builder setFirstName(String firstName) {
person.firstName = firstName;

return this;
}

// other setters ...

public Person build() {
if (null == person.firstName) {
throw new IllegalStateException("Invalid data.");
}

return person;
}
}
}

2)使用对象的属性来构建而不是直接在构建器中构建对象(并在build()方法中创建):

public class Person {
private String firstName;
// other properties ...

private Person() {}

// getters ...

public static class Builder {
// person properties instead of object
private String firstName;
// other properties ...

public Builder() {}

public Builder setFirstName(String firstName) {
this.firstName = firstName;

return this;
}

// other setters ...

public Person build() {
if (null == this.firstName) {
throw new IllegalStateException("Invalid data.");
}

Person person = new Person();
person.firstName = firstName;

return person;
}
}
}

我更喜欢第一种方式,因为我认为有很多属性在构建器中重复它们是多余的。第一种方法有什么缺点吗?

提前致谢,抱歉我的英语不好。

最佳答案

小提示:是的,属性可能是重复的,但它们有优点

详情如下:如果你看细节here .

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

这里的问题是,因为对象是通过多次调用创建的,它可能在构建过程中处于不一致状态。这也需要付出很多额外的努力来确保线程安全。

更好的选择是使用构建器模式。

注意以下 Builder 中的方法和各自的构造函数或父 Pizza 类 - 链接中的完整代码 here

 public static class Builder {

public Pizza build() { // Notice this method
return new Pizza(this);
}
}

private Pizza(Builder builder) { // Notice this Constructor
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}

关于Java实现构建器模式的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23169505/

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