简体   繁体   中英

How to implement Inheritance of builder pattern in java

The Next snippet show how to implement a basic builder pattern in Java.

public class User {
private final String firstName; // required
private final String lastName; // required
private final int age; // optional
private final String phone; // optional
private final String address; // optional

private User(UserBuilder builder) {
    this.firstName = builder.firstName;
    this.lastName = builder.lastName;
    this.age = builder.age;
    this.phone = builder.phone;
    this.address = builder.address;
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

public int getAge() {
    return age;
}

public String getPhone() {
    return phone;
}

public String getAddress() {
    return address;
}

public static class UserBuilder {
    private final String firstName;
    private final String lastName;
    private int age;
    private String phone;
    private String address;

    public UserBuilder(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public UserBuilder age(int age) {
        this.age = age;
        return this;
    }

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

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

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

}

Q: if i have more then one model of User class ,with the same super class (like abstract/non abstract SuperUser as super class,and UserA , UserB, UserC extends it), how can i implement the builder with less code than add specific builder for each class, i like to create one builder for all of the subclass

Thnaks

Two possibilities come to mind:

  1. Create a derived builder class for each derived class and add overloads for all methods, returning the derived builder class as a return value, but otherwise just call the super class' method. This works in Java because of the covariance of inherited method return types. But this is also the solution that you seem to dislike.

    • or -
  2. Generify the builder class: Add a type parameter representing the concrete builder product class, and then add a static builder construction method to each of the derived product classes to return a properly parameterized instance of the builder class. This way, you save yourself the overloading of the builder methods just for the sake of their return type, and you can add subclasses of a builder class only if you really need them to initialize properties of a derived product class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM