建造者模式
用过lombok的人可能对这个创建型模式很熟悉了,通常我们使用@Builder注解的时候,就是lombok自动帮我们实现了建造者模式。
例如用户类举例:
import lombok.Builder;
@Builder
public class User {
private String username;
private String password;
}
使用:
public static void main(String[] args) {
User user = User.builder().username("zhangsan").password("123456").build();
}
实际编译后的代码:
public class User {
private String username;
private String password;
User(String username, String password) {
this.username = username;
this.password = password;
}
public static User.UserBuilder builder() {
return new User.UserBuilder();
}
public static class UserBuilder {
private String username;
private String password;
UserBuilder() {
}
public User.UserBuilder username(String username) {
this.username = username;
return this;
}
public User.UserBuilder password(String password) {
this.password = password;
return this;
}
public User build() {
return new User(this.username, this.password);
}
public String toString() {
return "User.UserBuilder(username=" + this.username + ", password=" + this.password + ")";
}
}
}