4

I have an API to subscribe a CAN signal as below :

bool subscribe(signal name);

SubscribeResponse(const CAN_DATA& data);

data.signal is the signal name

data.value is the signal value.

Now lets say client C1 and client C2 subscribe to different signal s1 and s2 respectively.

if any signal s1 or s2 changed response is received on SubscribeResponse(const CAN_DATA& data);

client c1 and c2 will will be added as obserber as below

 AddObserver(CanClient* observer) {
  observerlist.push_back(observer);
}

All the added observer will receive notification on change in the signal value as below :

void SubscribeResponse(const CAN_DATA& data){
std::vector<CanClient*>::iterator iter = observer_list_.begin();
  for (; iter != observerlist.end(); ++iter)
  (*iter)->NotifyEvent(data.signal,data.Value);
}

How can notification be send only to the actual subscriber ie if s1 changed notify to its subscriber c1 not c2 ?

leuage
  • 566
  • 3
  • 17

1 Answers1

4

The idea behind observer pattern is to allow loose coupling so that the observed(subject) shouldn't have to have any knowledge about the observers. Instead, you can notify all observers and then let the observers choose based on the information, whether or not to react to the notification received.

In NotifyEvent method you could react to the CAN_DATA information and process only if its the desired signal.

There are other ways to implement this, one possible approach could be visitor pattern, choose the signal "type" at run-time.

P0W
  • 46,614
  • 9
  • 72
  • 119