实施生成器模式时无法将字符串转换为生成器类错误

时间:2019-04-18 13:28:27

标签: java design-patterns

在实施构建器模式时无法将String转换为Builder类错误。请让我知道我在做什么错以及在哪里。谢谢。

打包BuilderDesignPattern;

公共类员工{

private final int id;
private String Name;
private String Address;

private Employee(EmployeeBuilder empB){

//此行类型不匹配出现错误,无法将字符串转换为Employee.EmployeeBuilder。

    this.id = empB.getId();
    this.Name = empB.getName();
    this.Address = empB.getAddress();

}

public static class EmployeeBuilder{

    private int id;
    private String Name;
    private String Address;
    public EmployeeBuilder setId(int id) {
        this.id = id;
        return this;
    }
    public EmployeeBuilder setName(String name) {
        Name = name;
        return this;
    }
    public EmployeeBuilder setAddress(String address) {
        Address = address;
        return this;
    }
    public EmployeeBuilder getId() {
        return this;
    }
    public EmployeeBuilder getName() {
        return this;
    }
    public EmployeeBuilder getAddress() {
        return this;
    }

    public Employee build(){

        return new Employee(this);
    }

}

}

2 个答案:

答案 0 :(得分:1)

您的吸气剂是错误的,没有返回正确的字段。应该是这样的:

public int getId() {
    return this.Id;
}
public String getName() {
    return this.Name;
}
public String getAddress() {
    return this.Address;
}

P.S .:在Java中,有一个约定以小写字母命名字段。

P.S.2:这不是一流的生成器,因为该类“了解”生成器。

答案 1 :(得分:0)

您的吸气剂不应返回this

它应该返回属性。

public class EmployeeBuilder{

    private int id;
    private String Name;
    private String Address;

    public EmployeeBuilder setId(int id) {
        this.id = id;
        return this;
    }

    public EmployeeBuilder setName(String name) {
        Name = name;
        return this;
    }

    public EmployeeBuilder setAddress(String address) {
        Address = address;
        return this;
    }

    public EmployeeBuilder getId() {
        return id;
    }

    public EmployeeBuilder getName() {
        return Name;
    }

    public EmployeeBuilder getAddress() {
        return Address;
    }

    public Employee build(){
        return new Employee(this);
    }

}