在Java中:如何创建一个可以初始化并在一个语句中调用其方法的类?

时间:2016-06-28 14:09:55

标签: java oop

在使用Google服务库时,我在Android编程中看到了很多编码风格,他们在初始化类的实例后使用点来调用方法。

例如,假设我有一个Person类:

public class Person {
    private String firstName;
    private String lastName;    
    private String occupation;
    private String primarySkill;
    private String secondarySkill;

/* ******************
 *   CONSTRUCTOR
 * ******************/
    public Person(String firstName, String lastName) {
        setFirstName(firstName);
        setLastName(lastName);
    }

/* ******************
 *     MUTATORS
 * ******************/
    // firstName Setter:
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    // lastName Setter:
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    // occupation Adder:
    public void addOccupation(String occupation) {
        this.occupation = occupation;
    }

    // primarySkill Adder:
    public void addPrimarySkill(String primarySkill) {
        this.primarySkill = primarySkill;
    }

    // secondarySkill Adder:
    public void addSecondarySkill(String secondarySkill) {
        this.secondarySkill = secondarySkill;
    }   
}

现在,当我创建此类的实例时,我希望能够执行以下操作:

Person bob = new Person("Bob", "Anderson")
            .addOccupation("Student")
            .addPrimarySkill("Java")
            .addSecondarySkill("SQL");

然而,这给了我语法错误。我怎样才能建立一个可以让我这样做的课程?

3 个答案:

答案 0 :(得分:8)

您正在寻找的内容称为Method Chaining。修改您的setter以返回this

// occupation Adder:
public Person addOccupation(String occupation) {
    this.occupation = occupation;
    return this;
}

答案 1 :(得分:1)

你应该有" setter"返回对象类型的方法。要构建addXyx方法:

public Person setLastName(String lastName) {
    this.lastName = lastName;
    return this;
}

public Person addOccupation(String occupation) {
    this.occupation = occupation;
    return this;
}

public Person addPrimarySkill(String primarySkill) {
    this.primarySkill = primarySkill;
    return this;
}

public Person addSecondarySkill(String secondarySkill) {
    this.secondarySkill = secondarySkill;
    return this;
} 

有了它,你可以链接你的setter调用:

Person bob = new Person("Bob", "Anderson")
        .addOccupation("Student")
        .addPrimarySkill("Java")
        .addSecondarySkill("SQL");

答案 2 :(得分:1)

这是使用Builder Pattern的典型案例。构建器模式中的setter返回 this