美文网首页
建造者模式

建造者模式

作者: virsus | 来源:发表于2020-04-27 18:11 被阅读0次

    实现

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

    总结

    • 使用静态内部类和静态方法可以直接通过类方法调用
    • 封装对象构建细节
    • 适用于构建对象时有特殊逻辑操作

    相关文章

      网友评论

          本文标题:建造者模式

          本文链接:https://www.haomeiwen.com/subject/jneuwhtx.html