我正在学习构建器模式。我有一个问题,为什么不使用一个类(例如:MyCoffe)而不是 2 个类(例如:MyCoffe、BuilderClass)。感谢您的阅读。
package Creational.Builder;
public class MyCoffe {
private String name;
private int id;
public MyCoffe(){
}
public MyCoffe setName(String newName){
this.name = newName;
return this;
}
public MyCoffe setId(int newId){
this.id = newId;
return this;
}
public MyCoffe build(){
return this;
}
public String toString(){
return name + "/" + id;
}
public static void main(String[] args){
MyCoffe myCoffe = new MyCoffe().setName("HelloWorld").setId(9999);
System.out.println(myCoffe);
System.out.println("Thanks for help!");
}
}
最佳答案
在某些特定情况下,您当然可以,但构建器模式的目的之一是避免类的无效实例。所以除非它对 MyCoffe
有效没有名称或 ID,您不希望它的实例在没有名称或 ID 的情况下运行,如下所示:
MyCoffe invalid = new MyCoffe();
另请注意,当类(class)像那样自建时,很容易忘记调用最终的 build
。方法(事实上,您在 main
中所做的),因此该实例永远不会得到验证。
因此在构建完整、有效的实例之前使用单独的构建器来保存不完整的信息。
在 Java 中,构建器是静态嵌套类的情况并不少见:
public class MyCoffe {
public static class Builder {
private String name;
private int id;
public Builder() {
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setId(int id) {
this.id = id;
return this;
}
public MyCoffe build() {
if (this.name == null) {
throw new AppropriateException("'name' is required");
}
if (this.id == 0) { // Assumes 0 isn't a valid ID
throw new AppropriateException("'id' is required");
}
return new MyCoffe(name, id);
}
}
private String name;
private int id;
public MyCoffe(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public String toString(){
return name + "/" + id;
}
public static void main(String[] args){
MyCoffe myCoffe = new MyCoffe.Builder().setName("HelloWorld").setId(9999).build();
System.out.println(myCoffe);
System.out.println("Thanks for help!");
}
}
或者如果像那样声明属性两次让您感到困扰,MyCoffe
可以允许私有(private)不完整的实例,像这样:
public class MyCoffe {
public static class Builder {
private MyCoffe instance;
public Builder() {
this.instance = new MyCoffe();
}
public Builder setName(String name) {
this.instance.name = name;
return this;
}
public Builder setId(int id) {
this.instance.id = id;
return this;
}
public MyCoffe build() {
if (this.instance.name == null) {
throw new AppropriateException("'name' is required");
}
if (this.instance.id == 0) { // Assumes 0 isn't a valid ID
throw new AppropriateException("'id' is required");
}
return this.instance;
}
}
private String name;
private int id;
private MyCoffe() {
}
public MyCoffe(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public String toString(){
return name + "/" + id;
}
public static void main(String[] args){
MyCoffe myCoffe = new MyCoffe.Builder().setName("HelloWorld").setId(9999).build();
System.out.println(myCoffe);
System.out.println("Thanks for help!");
}
}
关于java - 只有一个类的构建器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41365582/