gpt4 book ai didi

java - Builder Pattern inside vs outside类?

转载 作者:搜寻专家 更新时间:2023-10-31 19:39:25 25 4
gpt4 key购买 nike

<分区>

在类内和类外使用构建器模式有什么优势?

内部类:

public class Person {
private String name;
private String eyeColor;
private String hairColor;

public Person setName(String name) {
this.name = name;
return this;
}

public Person setEyeColor(String eyeColor) {
this.eyeColor = eyeColor;
return this;
}

public Person setHairColor(String hairColor) {
this.hairColor = hairColor;
return this;
}
}

// Example usage:
Person p = new Person()
.setName("Bob")
.setHairColor("Black")
.setEyeColor("Brown")

课外:

public class Person {
private String name;
private String eyeColor;
private String hairColor;

public Person(String name, String eyeColor, String hairColor) {
this.name = name;
this.eyeColor = eyeColor;
this.hairColor = hairColor;
}
}

public class PersonBuilder {
private String name;
private String eyeColor;
private String hairColor;

public Person build() {
return new Person(name, eyeColor, hairColor);
}

public PersonBuilder with(String name) {
this.name = name;
return this;
}

public PersonBuilder setEyeColor(String eyeColor) {
this.eyeColor = eyeColor;
return this;
}

public PersonBuilder setHairColor(String hairColor) {
this.hairColor = hairColor;
return this;
}
}

// Example usage:
Person p = new PersonBuilder()
.setName("Bob")
.setHairColor("Black")
.setEyeColor("Brown")
.build();

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