【发布时间】:2013-05-07 23:02:53
【问题描述】:
我有一个类似的类层次结构:
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
如何让通知者只通知教职员工或只通知学生? 提前致谢!
【问题讨论】:
标签: c# oop observer-pattern