dimanche 13 mai 2018

How to use observer pattern correctly?

I am learning design patterns. But when I studied observer pattern, a question came to my mind.

A typically observer pattern has following compenents:

  • Subject: An object holds some information acquired by Observer.
  • Observer: The object that monitors Subject. When some events happen, subject will inform observer.

My question is why it is Subject's duty to decide when to call observer. In my site, I think the condition should be chosen by observer.

Take the water heater as a simple example. A temperature monitor(observer) will alert, when the temperature is up to 95. So I can use the following code to describe this model.

namespace Heater
{
     public class Heater{   // subject
          private int temperature;
          public delegate void BoilHandler(int para);
          public event BoilHandler BoilEvent;

          public void BoilWater(){
               for (int i = 0; i <= 100; i++)
               {
                    temperature = i;
                    if(temperature > 95){   //decide when to inform observer
                         BoilEvent(temperature);
                    }
               }
          }
     }

     public class Alarm{    // observer
          public void MakeAlert(int param){
               Console.WriteLine("ALarm: UP TO 95, NOW is {0}", param);
          }
     }
}

So in observer pattern, I seperate Alarm from Heater. The implement of alarm depends on customer. But when I want to change the alarming threshold, I must change the code in class Heater rather than class Alarm.

Aucun commentaire:

Enregistrer un commentaire