【发布时间】:2020-12-13 09:02:12
【问题描述】:
假设我有一个汽车制造商,其参数包括型号、颜色和速度:
public class Car {
private String model;
private int color;
private int speed;
public Car(String model, int color, int speed) {
this.model = model;
this.color = color;
this.speed = speed;
}
//..Getters
public static class Builder {
private String model;
private int color;
private int speed;
public Builder model(String model) {
this.model = model;
return this;
}
public Builder color(int color) {
this.color = color;
return this;
}
public Builder speed(int speed) {
this.speed = speed;
return this;
}
public Car build() {
return new Car(model, color, speed);
}
}
}
我制造这样的汽车:
Car car1 = new Car.Builder()
.model("Audi")
.color(Color.RED.getRGB())
.speed(200)
.build();
Car car2 = new Car.Builder()
.model("Audi")
.color(Color.RED.getRGB())
.speed(350)
.build();
Car car3 = new Car.Builder()
.model("Audi")
.color(Color.RED.getRGB())
.speed(175)
.build();
如您所见,我的参数必须不断重复。我希望能够基于一些现有的空白制造新车,如下所示:
Car car1 = new Car.Builder()
.initFrom(redAudi)
.speed(200)
.build();
Car car2 = new Car.Builder()
.initFrom(redAudi)
.speed(350)
.build();
Car car3 = new Car.Builder()
.initFrom(redAudi)
.speed(175)
.build();
}
有没有提供这个的模板?
【问题讨论】:
标签: java builder-pattern