建造者模式

建造者模式

定义:建造者模式又被称为生成器模式,这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

@Slf4j
@ToString
//@Builder 工作中可使用该注解直接生成建造者
public class UserInfo {

    private Long userId;
    private String userName;
    private Long cityId;
    private String cityName;
    private String idCard;

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setCityId(Long cityId) {
        this.cityId = cityId;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public void setIdCard(String idCard) {
        this.idCard = idCard;
    }

    public static UserInfo.Builder builder() {
        return new UserInfo.Builder();
    }

    public static class Builder {
        private final UserInfo userInfo;

        public Builder() {
            this.userInfo = new UserInfo();
        }

        public Builder userId(Long userId) {
            userInfo.setUserId(userId);
            return this;
        }

        public Builder userName(String userName) {
            userInfo.setUserName(userName);
            return this;
        }

        public Builder cityId(Long cityId) {
            userInfo.setCityId(cityId);
            return this;
        }

        public Builder cityName(String cityName) {
            userInfo.setCityName(cityName);
            return this;
        }

        public Builder idCard(String idcard) {
            userInfo.setIdCard(idcard);
            return this;
        }

        public UserInfo build() {
            return this.userInfo;
        }

    }

    public static void main(String[] args) {
        //使用建造者模式之前
        UserInfo beforeUserInfo = new UserInfo();
        beforeUserInfo.setIdCard("idCard");
        beforeUserInfo.setUserName("tom");
        beforeUserInfo.setCityName("NewYork");
        beforeUserInfo.setCityId(1L);
        beforeUserInfo.setUserId(1L);
        log.info("beforeUserInfo:{}", beforeUserInfo);

        //使用建造者模式之后
        UserInfo afterUserInfo = UserInfo.builder().idCard("idCard").userName("tom").userName("tom").cityName("NewYork").cityId(1L).userId(1L).build();
        log.info("afterUserInfo:{}", afterUserInfo);
    }

}
上一篇:EF操作_使用实体添加数据库的用户信息


下一篇:Flutter37,互联网行业“中年”危机