确实很想知道怎么改写成一个builder模式? 能否给个完整代码
来源:9-4 创建对象

音乐流星
2020-10-23
2回答
-
ccmouse
2020-10-29
Employee类的实现
public class Employee {
private final String name;
private final int salary;
private Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public int getSalary() {
return salary;
}
public static class Builder {
private String name;
private int salary;
public Builder withName(String name) {
this.name = name;
return this;
}
public Builder withSalary(int salary) {
this.salary = salary;
return this;
}
public Employee Build() {
return new Employee(name, salary);
}
}
public static Builder newBuilder() {
return new Builder();
}
public static Builder fromExisting(Employee e) {
return new Builder().withName(e.name).withSalary(e.salary);
}
}使用代码:
Employee oldEmployee = Employee.newBuilder().withName("abc").withSalary(10000).Build();
Employee employee = Employee.fromExisting(oldEmployee).withSalary(15000).Build();10 -
音乐流星
提问者
2020-10-30
非常感谢
00
相似问题