Search code examples
c#oopobserver-pattern

notify only certain observers c#


I have a class hierarchy something like that:

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()); }
}

The code creates Student_1 , Student_2 and Staff_1 when started. Person class has single observer interface. Notifier has to notify: Staff only when factor has changed; Students only when question number has changed; Here's a code I have for that :

public void Notify()
    {
        foreach (IPerson o in observers)
        {

            if (o is Student) { o.Update(QuestionNumber); }
             else if (o is Staff) { o.Update(Factor); }
        }
    }

But the problem is that whatever is changed (question number or factor) whole bunch gets notified, like so :

  • Student_1 notified that question number is 1
  • Student_2 notified that question number is 1
  • Staff_1 notified that factor is current_factor

What to do to make notifier notify only Staff or only Students? Thanks in advance!


Solution

  • You need separate subscribe / notifies for the different things that change. Then staff subscribe to Factor events and students subscribe to question events.

    This will also mean you won't need to cast.

    your IPerson can have a UpdateQuestion and an UpdateFactor method.

    I presume you are doing this as an exercise because C# events are really the way to do this in normal .NET coding.