码迷,mamicode.com
首页 > 其他好文 > 详细

利用构建器创建对象

时间:2020-05-10 15:06:21      阅读:41      评论:0      收藏:0      [点我收藏+]

标签:pack   public   his   word   style   address   对象   void   ret   

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创建对象.

利用构建器创建对象

标签:pack   public   his   word   style   address   对象   void   ret   

原文地址:https://www.cnblogs.com/lishuaiqi/p/12863027.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!