我从一个在线视频教程中学习Java的设计模式。我已经学习了构建器设计模式,我正在尝试实现它所做的事情,但对我来说,它显示了一些错误。帮我解决这些问题。
public class Phone {
private String model;
private String os;
private int ram;
private double screensize;
private int battery;
public Phone(String model, String os, int ram, double screensize, int battery) {
super();
this.model = model;
this.os = os;
this.ram = ram;
this.screensize = screensize;
this.battery = battery;
}
@Override
public String toString() {
return "Phone [model=" + model + ", os=" + os + ", ram=" + ram + ", screensize=" + screensize + ", battery="
+ battery + "]";
}
}
public class Phonebuilder {
private String model;
private String os;
private int ram;
private double screensize;
private int battery;
public Phonebuilder setModel(String model) {
this.model = model;
return this;
}
public Phonebuilder setOs(String os) {
this.os = os;
return this;
}
public Phonebuilder setRam(int ram) {
this.ram = ram;
return this;
}
public Phonebuilder setScreensize(double screensize) {
this.screensize = screensize;
return this;
}
public Phonebuilder setBattery(int battery) {
this.battery = battery;
return this;
}
public Phone getphone () {
return new Phone(model, os, ram, screensize, battery);
}
}
public class Test {
public static void main(String[] args) {
//It showing error in the below line like type mismatch.
Phone p = new Phonebuilder().setBattery(9000).setModel("M31").setOs("Android");
System.out.println(p);
}
}发布于 2020-07-19 15:00:30
您缺少了构建对象的方法调用(getphone())
Phone p = new Phonebuilder()
.setBattery(9000)
.setModel("M31")
.setOs("Android")
.getphone(); //This builds and returns a Phone instanceSidenote: IMO buildPhone可能是个更好的名字。
发布于 2020-07-19 15:00:41
最后一个被调用的setOs方法返回Phonebuilder,但是您将它分配给Phone。我想目的是在设置所有参数之后添加getPhone。
发布于 2020-07-19 15:46:38
我不认为在使用构建器模式时在Phone类中提供公共构造函数是个好主意。使用构建器模式的原因是为了解决与大量可选参数相关的问题。下面是您的示例的替代方法(它基于图书“有效Java”中的第2项'当面对许多构造函数参数时,请考虑构建器 )。这种方法的一个优点是,电话类是不可变的,即一旦创建,它就不能更改。
public class Phone {
private final String model;
private final String os;
private final int ram;
private final double screensize;
private final int battery;
private Phone(Builder builder) {
model = builder.model;
os = builder.os;
ram = builder.ram;
screensize = builder.screensize;
battery = builder.battery;
}
public static class Builder {
private String model;
private String os;
private int ram;
private double screensize;
private int battery;
public Builder calories(String val) {
model = val;
return this;
}
public Builder os(String val) {
os = val;
return this;
}
public Builder ram(int val) {
ram = val;
return this;
}
public Builder screensize(double val) {
screensize = val;
return this;
}
public Builder battery(int val) {
battery = val;
return this;
}
public Phone build() {
return new Phone(this);
}
}
}创建电话生成器作为-
Phone phone =
new Phone.Builder()
.battery(1)
.calories("100")
.os("windows")
.screensize(15)
.battery(2)
.build();https://stackoverflow.com/questions/62981841
复制相似问题