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);
                










