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