We help IT Professionals succeed at work.
Get Started

Need to pass data with notification in the observer design pattern

boycy
boycy asked
on
657 Views
Last Modified: 2013-11-12
I am implementing a system using the observer pattern to decouple my data generating/modifying code from the data handling code. As there are different notifications my notify method takes a 'message' parameter; if I make this a struct

I need to pass some data with the notification - there are several different types of change that can occur, so my
There is additional data that I feel should be provided with the call to notify(), in particular the updated data.

Looking at the code below, does anyone have any feeling on the alternatives I propose, or can suggest something different? I'm not sure I've explained it supremely well, let me know if I can clarify.

TIA,
--rob
struct Message
{
   virtual ~Message(void) {}
};
 
 
// methods not referred to are omitted
struct IMessageObserver
{
   virtual void notify(const Message& msg) = 0;
   virtual void notify2(const Message& msg, void* data) = 0;
};
 
 
struct MessageWithoutData
   : public IMessage
{
} MSG_NO_DATA; // no members and this instance mean I can compare (msg == MSG_NO_DATA) to determine what notification I've been given
 
 
struct MessageWithData
   : public IMessage
{
   MessageWithData(int newValue)
      : value(newValue)
   {}
 
   int value;
} // can't do a straightforward comparison in notify() now - RTTI instead?
 
 
// the example notifications
void doANotification(IMessageObserver& observer)
{
   int newValue(24);
 
   // should I construct with the data?
   observer.notify(MessageWithData(newValue));
 
   // or pass the data separately
   observer.notify2(MSG_NO_DATA, &newValue);
}

Open in new window

Comment
Watch Question
CERTIFIED EXPERT
Top Expert 2009
Commented:
This problem has been solved!
Unlock 4 Answers and 17 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE