我有一个类似的类层次结构:
public class Staff : Person
{
public Staff() {}
public Staff(string id): base(id) {}
public override void Update(object o) { Console.WriteLine(id + " notified that Factor is {1} .", id, o.ToString()); }
}
public class Student : Person
{
public Student() {}
public Student(string id): base(id) {}
public override void Update(object o) { Console.WriteLine(id +" notified that Question is {1} .", id, o.ToString()); }
}
public abstract class Person : IPerson
{
protected string id;
public Person() { }
public Person(string i) { this.id = i; }
public abstract void Update(Object o); // { Console.WriteLine(id +" notified about {1} .", id, o.ToString()); }
}
代码在启动时创建 Student_1 、 Student_2 和 Staff_1 。Person 类具有单个观察者接口。通知人必须通知:只有在因素发生变化时才通知员工;学生仅在问题编号发生变化时;这是我的代码:
public void Notify()
{
foreach (IPerson o in observers)
{
if (o is Student) { o.Update(QuestionNumber); }
else if (o is Staff) { o.Update(Factor); }
}
}
但问题是,无论发生什么变化(问题编号或因素),都会收到通知,如下所示:
- Student_1 通知问题编号为 1
- Student_2 通知问题编号为 1
- Staff_1 通知因子是 current_factor
怎么做才能让通知者只通知员工或只通知学生?提前致谢!