如何在两个类之间发送/接收消息

时间:2018-12-18 22:14:48

标签: c++

我有两个类source和destination,它们代表了两个我想在它们之间发送和接收消息的主机。为了做到这一点,我创建了以下类。有一个更好的方法吗 ? 例如:

       class   Reseux
  {
   private:
         int Nb_Source;
         int Nb_destination;

   public:
          class  Source
                {
                 private:
                         int id_Source;

                 public:
                      void __fastcall Envoyer();
                      void __fastcall Recevoir();
                      int __fastcall get_id() {return (this->id_Source);};
                } *Source;
        //---------------------------------------------------------------- 
          class  destination;
                {
                 private:
                         int id_destination;;

                 public:
                      void __fastcall Envoyer();
                      void __fastcall Recevoir();
                      int __fastcall get_id() {return (this->id_destination);};
                } *destination;              
  };
  class tMessage
  {
   private:
           String Contenu;
           int id_Source, id_Destination;
   public:
          bool Alert;
          int __fastcall get_id_Source() {return(this->id_Source);};
          int __fastcall get_id_Destination() {return(this->id_Destination);};
  };
void __fastcall Reseux::Source::Envoyer(tMessage *_Message)
{   _Message=new tMessage();
_Message->id_Source=Source->get_id();
_Message->id_destination=id_destination->get_id();
 destination->Recevoir(_Message);}
void __fastcall Reseux::destination::Recevoir(tMessage *_Message)
{   };

1 个答案:

答案 0 :(得分:0)

您可以尝试使用Observer模式,如下所示:

#include <string>
#include <iostream>
#include <memory>
#include <vector>

class Message
{
public:
    explicit Message(const std::string& text) : content(text) { }

    std::string GetText() const { return content; }

private:
    std::string content{ "" };
};

class Subscriber
{
public:
    explicit Subscriber() { }
    virtual ~Subscriber() { }

    virtual void ReceiveMsg(const Message& msg) = 0;
};

class Source
{
public:
    explicit Source() { }

    inline void BroadcastMsg(const std::string& content)
    {
        Message msg(content);

        for (const auto& subscriber : subscribers)
            subscriber->ReceiveMsg(msg);
    }

    inline void AddSubscriber(Subscriber* sub) { subscribers.push_back(sub); }

private:
    std::vector<Subscriber*> subscribers;
};

class Destination : public Subscriber
{
public:
    explicit Destination() { }
    virtual ~Destination() { }

    inline virtual void ReceiveMsg(const Message& msg) override 
    {
        std::cout << msg.GetText();
    }
};

int main()
{
    std::unique_ptr<Source> host1 = std::make_unique<Source>();
    std::unique_ptr<Destination> host2 = std::make_unique<Destination>();
    host1->AddSubscriber(host2.get());
    host1->BroadcastMsg("Good morning, Vietnam!!!");
    getchar();
}