0
点赞
收藏
分享

微信扫一扫

Java Builder模式的写法和lombok插件@Builder注解的支持


1. Builder模式简化get set方法,只需要定义一个静态公共的内部类即可

public class User {
private Integer id;
private String name;
private String address;

private User() {
}

private User(User origin) {
this.id = origin.id;
this.name = origin.name;
this.address = origin.address;
}

public static class Builder {
private User target;

public Builder() {
this.target = new User();
}

public Builder id(Integer id) {
target.id = id;
return this;
}

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

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

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



public class User {
private Integer id;
private String name;
private String address;

private User() {
}

private User(User origin) {
this.id = origin.id;
this.name = origin.name;
this.address = origin.address;
}

public static class Builder {
private User target;

public Builder() {
this.target = new User();
}

public Builder id(Integer id) {
target.id = id;
return this;
}

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

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

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

2.如果项目中有使用lombok的话,可以直接使用@Builder注解来实现

定义工具类如下:

import lombok.Builder;
import lombok.ToString;

/**
* @author wulongtao
*/
@ToString
@Builder
public class UserExample {
private Integer id;
private String name;
private String address;
}


import lombok.Builder;
import lombok.ToString;

/**
* @author wulongtao
*/
@ToString
@Builder
public class UserExample {
private Integer id;
private String name;
private String address;
}

使用方法:

UserExample userExample = UserExample.builder()
.id(1)
.name("aaa")
.address("bbb")
.build();

System.out.println(userExample);

UserExample userExample = UserExample.builder()
.id(1)
.name("aaa")
.address("bbb")
.build();

System.out.println(userExample);


举报

相关推荐

0 条评论