Builder设计模式:必需属性

时间:2014-10-26 10:01:06

标签: java design-patterns

将构建器上的必需属性定义为final是否很重要? (代码表现)

这是一个说明我的问题的例子:

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; // required
    private final String lastName;  // required
    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);
    }

}
}

1 个答案:

答案 0 :(得分:1)

简短的回答是“通常不是”。

  

您应该根据清晰的设计和可读性来使用final   而不是出于表现原因。

Does use of final keyword in Java improve the performance?