接下来,由于大多数小孩都有父母,还将添加两个字段来表示母亲和父亲,并增加适当的 accessor/mutator 方法。将为 Person 类增加一个新的方法,使之可以创建一个新的 Person,这个方法有一个贴切的名称,即 haveBaby。此外还增加一些业务规则,以支持生小孩的生物学需求,并将这个新的小 Person 添加到为母亲和父亲字段创建的 children ArrayList 中。做完这些之后,再将这个婴儿返回给调用者。
清单 2 显示,新定义的 Person 类可以处理这种多样性关系。
清单 2. 定义为多样性关系的家庭生活
package com.tedneward.model;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class Person
{
public Person()
{ }
public Person(String firstName, String lastName, Gender gender, int age, Mood mood)
{
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.age = age;
this.mood = mood;
}
public String getFirstName() { return firstName; }
public void setFirstName(String value) { firstName = value; }
public String getLastName() { return lastName; }
public void setLastName(String value) { lastName = value; }
public Gender getGender() { return gender; }
public int getAge() { return age; }
public void setAge(int value) { age = value; }
public Mood getMood() { return mood; }
public void setMood(Mood value) { mood = value; }
public Person getSpouse() { return spouse; }
public void setSpouse(Person value) {
// A few business rules
if (spouse != null)
throw new IllegalArgumentException("Already married!");
if (value.getSpouse() != null && value.getSpouse() != this)
throw new IllegalArgumentException("Already married!");
spouse = value;
// Highly sexist business rule
if (gender == Gender.FEMALE)
this.setLastName(value.getLastName());
// Make marriage reflexive, if it's not already set that way
if (value.getSpouse() != this)
value.setSpouse(this);
}
public Address getHomeAddress() { return addresses[0]; }
public void setHomeAddress(Address value) { addresses[0] = value; }
public Address getWorkAddress() { return addresses; }
public void setWorkAddress(Address&