建造者模式

2020-04-27  本文已影响0人  virsus

实现

public class User {
    private String id;

    private String name;

    private String phone;

    private String addr;

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

    public static class Builder {
        private String id;

        private String name;

        private String phone;

        private String addr;

        public User build() {
            User user = new User();
            user.id = this.id;
            user.name = this.name;
            user.phone = this.phone;
            user.addr = this.addr;
            return user;
        }

        public Builder id(String id) {
            this.id = id;
            return this;
        }
        public Builder name(String name) {
            this.name = name;
            return this;
        }
        public Builder phone(String phone) {
            this.phone = phone;
            return this;
        }
        public Builder addr(String addr) {
            this.addr = addr;
            return this;
        }
    }

    public static void main(String[] args) {
        User user = User.builder().id("1").name("2").addr("3").phone("4").build();
    }
}

总结

上一篇下一篇

猜你喜欢

热点阅读