我正在通过在线视频教程学习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);
}
}
答案 0 :(得分:2)
您缺少对 build 对象(getphone()
)的方法调用
Phone p = new Phonebuilder()
.setBattery(9000)
.setModel("M31")
.setOs("Android")
.getphone(); //This builds and returns a Phone instance
旁注:IMO buildPhone
可能是一个更好的名字。
答案 1 :(得分:2)
最后调用的 setOs 方法返回 Phonebuilder ,但是您将其分配给 Phone 。我想目的是在设置所有参数后添加 getPhone 。
答案 2 :(得分:1)
我认为在使用构建器模式时在Phone类中提供公共构造函数不是一个好主意。使用构建器模式的原因是为了解决与大量可选参数相关的问题。以下是您示例的替代方法(基于有效Java书籍的第2项“ Consider a builder when faced with many constructor parameters'”)。这种方法的一个优点是电话类别是不可变的,即一旦创建便无法更改。
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();