我的构建器模式有什么问题?

时间:2015-07-08 10:45:47

标签: java design-patterns builder-pattern

我在构建Builder模式时遇到问题。 我有2个班级:

package course_2;

import java.util.Date;

public class Student {
    private static int idStart = 0;

    private final int id = idStart++;
    private String name;
    private String surname;
    private String secondName;
    private Date birthDate;
    private String address;
    private String phone;
    private int course;
    private int group;

    public static class Builder {
        // Обязательные параметры
        private final String name;
        private final String surname;
        private final Date birthDate;
        // Необязательные параметры, инициализация по умолчанию
        private String secondName = "";
        private String address = "";
        private String phone = "";
        private int course = 1;
        private int group = 1;

        public Builder(String name, String surname, Date birthDate) {
            this.name = name;
            this.surname = surname;
            this.birthDate = (Date) birthDate.clone();
        }

        public Builder SecondName(String secondName) {
            this.secondName = secondName;
            return this;
        }

        public Builder address(String address) {
            this.address = address;
            return this;
        }

        public Builder phone(String phone) {
            this.phone = phone;
            return this;
        }

        public Builder course(int course) {
            this.course = course;
            return this;
        }

        public Builder group(int group) {
            this.group = group;
            return this;
        }
    }

    private Student(Builder builder) {
        this.name = builder.name;
        this.surname = builder.surname;
        this.secondName = builder.secondName;
        this.birthDate = builder.birthDate;
        this.address = builder.address;
        this.phone = builder.phone;
        this.course = builder.course;
        this.group = builder.group;
    }
}

问题是当我尝试从客户端代码调用Builder时:

Student studentOne = new Student.Builder("Andrue", "Booble", /*Date variable here*/);

我遇到编译问题:

  

错误:(24,30)java:不兼容的类型:course_2.Student.Builder   无法转换为course_2.Student

有人可以帮助我理解,为什么会发生这种情况以及我如何解决它?谢谢!

2 个答案:

答案 0 :(得分:2)

您需要将以下内容添加到Builder

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

并称之为:

    Student studentOne = new Student.Builder("Andrue", "Booble", null).build();

答案 1 :(得分:1)

new Student.Builder("Andrue", "Booble", /*Date variable here*/);会返回构建器对象而非学生。

您的工厂缺少调用学生构造函数

的方法create

它看起来应该是这样的

 public Student create(){
 return new student (this);
 }

并在Builder

中实现

现在,如果您想创建学生,请致电

Student studentOne = new Student.Builder("Andrue", "Booble", /*Date variable here*/).create();