gpt4 book ai didi

java 构造函数处理缺少参数的情况

转载 作者:行者123 更新时间:2023-12-01 08:04:30 25 4
gpt4 key购买 nike

我在这里有一个人详细信息的代码,并且无论给出多少可能的参数,都应该始终初始化该人,例如仅高度和年龄或薪水和年龄
我发现很难为每个参数组合声明一个构造函数,是否有比这更优化的解决方案?

class person {
public static final int defalut_salary=1000;
public static final int default_age=20;
public static final double default_height=6;
public static final String default_name="jack";

protected int salary;
protected int age;
protected double height;
protected String name;

person(){
}
}

最佳答案

我建议使用Builder模式:

public final class Person {
private final int salary;
private final int age;
private final double height;
private final String name;

public Person(int salary, int age, double height, String name) {
this.salary = salary;
this.age = age;
this.height = height;
this.name = name;
}

// Getters or whatever you want

public static class Builder {
// Make each field default appropriately
private int salary = 1000;
private int age = 20;
private double height = 6;
private String name = "jack";

public Builder setSalary(int salary) {
this.salary = salary;
return this;
}

// Ditto for other properties

public Person build() {
return new Person(salary, age, height, name);
}
}
}

用法:

Person person = new Person.Builder().setAge(25).setHeight(15).build();

您可以在 Person 构造函数中执行验证,如果您想要将任何字段设为必填,您可以在 Builder 中获取这些字段 构造函数。

关于java 构造函数处理缺少参数的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22687042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com