0

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 ?

Coodie_d
  • 35
  • 6

1 Answers1

0

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.
Donghui Zhang
  • 1,133
  • 6
  • 8
  • it would work if I didn't need to give the information from packet.information to the GUI – Coodie_d Oct 19 '16 at 20:54
  • In my solution, there is nothing preventing you from calling Gui::UpdateInformation with arguments. – Donghui Zhang Oct 19 '16 at 20:57
  • But Gui::UpdateInformation is supposed to be called in Protocol::readPacket actually. – Coodie_d Oct 19 '16 at 21:04
  • Think of the idea I gave you as a high-level guideline how things should be done. Adjust it based on your context. If you need to call Gui::UpdateInformation in Protocol::readPacket, you may keep the unordered_map as a static variable inside a static member function of Protocol. In Procolol::readPacket, call that static member function to get the unordered_map. – Donghui Zhang Oct 19 '16 at 21:12