我在这里有一个人员详细信息的代码,无论给出多少可能的参数,这个人都应该初始化,例如只有身高和年龄或工资和年龄
并且我发现很难为每个参数组合声明一个构造函数,是否有一个更优化的解决方案?
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(){
}
}
答案 0 :(得分:6)
我建议使用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
构造函数中使用这些字段。
答案 1 :(得分:0)
您可以将构造函数定义为采用原始包装类(如java.lang.Integer或java.lang.Double)而不是基元。不同之处在于,这允许您传递null
而不是值。然后,您可以检查null
。如果为null,则指定默认值。如果他们不是,你可以分配他们的价值。
public Person(Integer salary, Integer age, Double height, String name) {
if (salary == null) this.salary = salary else this.salary = default_salary;
if (age == null) this.age = age else this.age = default_age;
//...
}
调用new Person(1200, null, 5.3, null);
意味着"创建一个起薪1200,默认年龄,身高5.3和默认名称"的人。
另一种方法是使用builder pattern,如Jon Skeet的回答所示。它不那么简洁,但更具可读性。
答案 2 :(得分:0)
初始化默认构造函数中的所有字段,并使用方法在所需字段中设置值,例如:
class A{
Field a;
Field b;
Field c;
public A(){
a = SOME_VALUE;
b = SOME_VALUE;
c = SOME_VALUE;
}
public A withA(Field a){ this.a = a; return this; }
public A withB(Field b){ this.b = b; return this; }
public A withC(Field c){ this.c = c; return this; }
/* other code */
}
然后你可以像这样使用它:
A a = new A().withB(SOME_OTHER_VALUE).withC(YET_DIFFERENT_VALUE);
如果不想要这些字段'要通过后续调用withX()
方法来更改值,您可以使用完整的构建器模式。