Q:

c++ static observer class

I have two programs: a server and a client
class client
{
 private:
  Network    net;
  Gui        gui;
};

Here's the Network class
class Network
{
  public:
   void      receivePacket(packet)
   {
     Protocol::readPacket(packet)
   }
};

Here's the Gui class
class Gui
{
 private:
  std::string   informations;

 public:
  void          displayInfo();
  void          updateInformation(information);
};

And here's Protocol
class Protocol
{
     static void     readPacket(packet)
     {
       if (packet.command == "refreshGui")
         //I need somehow to call GUI::UpdateInformation here and give the information from packet.information
     }
};

Protocol is considered as a "static class" which means that in shouldn't be instantiate. So the idea is that, when Protocol::readPacket get a packet from the server, it should be able to send the information to the GUI. However, it's not always the case, so passing a point/reference is not what I'm looking for.
It's not well illustrated but the idea is:
- Protocol::readPacket seek if we need to call GUI
- Protocol shouldn't take another argument, and shouldn't be instantiate.
Someone gave me the advice about using Observer-pattern. Protocol would be the subject and GUI the Observer. However, I couldn't make it without instantiate Protocol.
So is there a way to do it without instantiate Protocol ?

A:

In distributed computing, it is a common pattern for the network manager of a node to receive a message and call a dispatcher associated with the message type. Your need is quite similar. Here is what you could do:

In your Network class, maintain an unordered_map< packet_type, std::function >.
When your program starts, push into that unordered_map an std::pair<"refreshGui", Gui::UpdateInformation>
In Network::receivePacket, retrieve the function from the unordered_map and call it.

