• 利用构建器创建对象


    1. 在创建类的时候,如果参数过多,我们直接使用构建起创建方法的时候会不知道具体参数代表什么类型.比如:

    User user = new User("123","123","123","123","123");

    这样不知道具体的参数代表什么,不容易知道要创建什么类型的User,所以我们可以直接使用构建器创建对象.

    2.比如这样:

    User user = new User.Builder().address("123").username("123").build();

    这样的话我们就可以直观的知道要创建什么字段.具体代码如下:

    package demo01;
    
    public class User {
        private String username;
        private String password;
        private String nickname;
        private String address;
        private String email;
    
        public static class Builder{
            private String username = "";
            private String password = "";
            private String nickname = "";
            private String address = "";
            private String email = "";
            
            public Builder username(String username) {
                this.username = username;
                return this;
            }
            
            public Builder password(String password) {
                this.password = password;
                return this;
            }
            
            public Builder nickname(String nickname) {
                this.nickname = nickname;
                return this;
            }
            
            public Builder address(String address) {
                this.address = address;
                return this;
            }
            
            public Builder email(String email) {
                this.email = email;
                return this;
            }
            
            public User build() {
                return new User(this);
            }
        }
        
        private User(Builder builder) {
            this.username = builder.username;
            this.password = builder.password;
            this.nickname = builder.nickname;
            this.email = builder.email;
            this.address = builder.address;
        }
        
        public static void main(String[] args) {
            User user = new User.Builder().address("123").username("123").build();
        }
    
    }

    定义了一个内部类,并且把构造函数private化,最后调用build()的方法在内部赋值.

    这样我们就可以直接使用Builder创建对象.

  • 相关阅读:
    正则表达式(RegExp)
    文本处理工具(cut,sort,tr,grep等)
    权限和ACL练习题
    访问控制列表ACL
    权限和ACL访问控制-02-特殊权限
    数据库的高级操作
    数据表三范式&范式理论
    数据表之间的关系
    数据表的列类型
    修改表结构
  • 原文地址:https://www.cnblogs.com/lishuaiqi/p/12863027.html
Copyright © 2020-2023  润新知