专业的JAVA编程教程与资源

网站首页 > java教程 正文

JAVA构造函数参数过多时,建议使用构建器

temp10 2024-10-17 16:22:18 java教程 10 ℃ 0 评论

构建器类

public class People {
 private final int id;
 private final int age;
 private final String name;
 private final String addr;
 public static class Builder{
 private final int id;
 private final String name;
 private int age = 0;
 private String addr = "";
 public Builder(int id, String name) {
 this.id = id;
 this.name = name;
 }
 public Builder age(int val){
 age = val;
 return this;
 }
 public Builder addr(String val){
 addr = val;
 return this;
 }
 public People build(){
 return new People(this);
 }
 }
 private People(Builder builder) {
 this.id = builder.id;
 this.age = builder.age;
 this.name = builder.name;
 this.addr = builder.addr;
 }
 public int getId() {
 return id;
 }
 public int getAge() {
 return age;
 }
 public String getName() {
 return name;
 }
 public String getAddr() {
 return addr;
 }
}

使用:

JAVA构造函数参数过多时,建议使用构建器

public static void main(String[] args) {
 //多个参数是使用构建器
 People p = new People.Builder(1, "张三").addr("北京").age(12).build();
 System.out.println(p.getAddr());
 }

这样在参数过多的时候就能清晰看清楚每个参数的意义。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表