0

I just started with learning the observer pattern in C# and my requirement is just the opposite of the observer pattern:

We have many processes running and a single process monitoring them all. Each and every process can (if some event happens) notify the parent process.

It seems that there is already this question "What is the opposite of the observer pattern?" which discusses this but still there is no code examples.

For understanding the observer pattern, i referred this code below by Jon Skeet at this answer.

Super-simple example of C# observer/observable with delegates

      using System;

      class Observable
      {
          public event EventHandler SomethingHappened;

          public void DoSomething()
          {
          EventHandler handler = SomethingHappened;
          if (handler != null)
          {
            handler(this, EventArgs.Empty);
          }
      }




      class Observer
      {
          public void HandleEvent(object sender, EventArgs args)
          {
             Console.WriteLine("Something happened to " + sender);
          } 
      }



    class Test
    {
        static void Main()
        {
        Observable observable = new Observable();
        Observer observer = new Observer();
        observable.SomethingHappened += observer.HandleEvent;

        observable.DoSomething();
        }
    }

Now let us assume we have only one observer (parent process) and many child processes. How does one implement this in observer pattern in c#. Does any other pattern can be used for this implementation ?

Thanks for your answers in advance.

Community
  • 1
  • 1
  • 1
    So why don't you just use the observer pattern? Each process implements the oberservable interface and the one process monitoring them all observes each process? Would be the cleanest solution imho – Coxer Jun 20 '13 at 09:20

1 Answers1

3

What problem are you trying to solve? The Observer pattern is about isolating observees from the observer and vice versa, giving you the flexibility to add new observees without modifying your observer. Just provide a delegate in the parent process for child processes to fire off when an interesting event occurs. It's a pretty classic fit for the Observer pattern, so I don't really get what you think is so 'opposite' of your scenario.

You should probably pass in the delegate when starting your child processes and let them hang on to the reference. That way, you won't have to provide a mechanism for child processes to find the parent process, either through the OS, through a Singleton or through global variables, any of which options tend to defeat unit testability.

As a side note, when the Observer pattern was first described, mainstream OO languages didn't have delegate-like functionality. In essence, delegates are Observers incorporated in the C# language and .NET platform.

Pontus Gagge
  • 16,731
  • 1
  • 36
  • 50