处理某些抽象类的子类的重载方法

MxL*_*evs 3 java

我有一个泛型Person类,两种类型的人,StudentTeacher扩展了Person类.我还有教学课程,将存储学生名单和将在该课程中的教师名单.

class Person {}
class Student extends Person {}
class Teacher extends Person {}

class Session {
  List<Student> students = new ArrayList();
  List<Teacher> teachers = new ArrayList();

  // add a person to the teaching session.
  // They should be placed into the appropriate lists
  public void enroll(Person p)
  {
    if (p instanceof Student)
      students.add((Student) p)
    else if (p instanceof Teacher)
      teachers.add((Teacher) p)
  }
}
Run Code Online (Sandbox Code Playgroud)

这个想法是,其他一些代码将有一个人员列表,并根据需要迭代列表以将其注册到适当的会话中.但是,该enroll方法当前显式检查对象的类型,这对我来说是不可取的,看起来像是糟糕的设计.

我尝试enroll使用方法重载编写这样的方法,看起来更干净

public void enroll(Student p)
{
    students.add(p)
}

public void enroll(Teacher p)
{
    teachers.add(p)
}
Run Code Online (Sandbox Code Playgroud)

但似乎迭代Person对象列表的代码需要确定当前人是学生还是教师实例,并在将其传递给enroll方法之前进行适当的类型转换.

有没有办法让我设计这个,以便我不需要instanceof在我自己的代码中随时调用?

Aar*_*als 7

  1. Session 需要像你的问题一样有一个重载的注册方法.
  2. abstract enroll向作为参数的Person类添加方法Session

    public abstract void enroll (Session s);

  3. TeacherStudent每个覆盖enroll

    public void enroll (Session s) {
         s.enroll(this);
    }
    
    Run Code Online (Sandbox Code Playgroud)