简体   繁体   English

调用没有硬编码参数的构造函数(耦合)

[英]Calling a constructor without hard coding parameters (coupling)

I have a method which creates a new object Student and adds it to an array list studentRegister: 我有一个创建新对象Student的方法,并将其添加到数组列表studentRegister:

public void addStudent(String name, String age)
{
     studentRegister.add(new Student(name, age));
}

it calls the Student class constructor here: 它在这里调用Student类构造函数:

public Student(String name, String age) 
{
  this.name = name;
  this.age = age;
}

This works but it is bad for maintainability as i have to change any additional parameters in both the Student class and the addStudent method. 这有效,但它对可维护性不利,因为我必须更改Student类和addStudent方法中的任何其他参数。 How do I input the parameters at the addStudent stage without having them harcoded in the addStudent method? 如何在addStudent阶段输入参数而不在addStudent方法中对它们进行编码?

just do this: 这样做:

public void addStudent(Student s)
{
     studentRegister.add(s);
}

And in constructer/ other methods you can call the above method as below: 在constructer / other方法中,您可以调用上面的方法如下:

public Student(String name, String age) 
{
  this.name = name;
  this.age = age;
  addStudent(this); //here is the call to the above method
}

You should pass a student object - Instead of the two values. 你应该传递一个学生对象 - 而不是两个值。

public void addStudent(Student student)
{
     studentRegister.add(student);
}

Using 运用

public void addStudent(final Student student) {
    studentRegister.add(student);
}

is the better aproach. 是更好的方法。

Maybe you're looking for a simpler way to build the object. 也许你正在寻找一种更简单的方法来构建对象。 eg using chain setters: 例如使用连锁装置:

public class Student {

    private String name;
    private String age;
    private String address;

    public String getName() {
        return name;
    }

    public Student setName(String name) {
        this.name = name;
        return this;
    }

    public String getAge() {
        return age;
    }

    public Student setAge(String age) {
        this.age = age;
        return this;
    }

    public String getAddress() {
        return address;
    }

    public Student setAddress(String address) {
        this.address = address;
        return this;
    }
}

So, would then: 那么,那么:

Student student = new Student().setName("User")
                               .setAge("30")
                               .setAddress("New York");

Another way for build the object with normal setters: 使用普通setter构建对象的另一种方法:

Student student = new Student(){{
    setName("User");
    setAge("30");
    setAddress("30");
}};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM