确实很想知道怎么改写成一个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();

1
0

音乐流星

提问者

2020-10-30

非常感谢

0
0

Google面试官亲授-Java面试新手尊享课

为面试新手量身定制的Java面试尊享课,解锁“鲤鱼跃龙门”的妙招

2853 学习 · 180 问题

查看课程