直接调用函数 vs 发射信号(Qt - 信号和槽)

Call function directly vs emiting Signal (Qt - Signals and Slots)

在这一点上,我陷入了两难境地:何时发出信号与直接调用另一个 class 中的方法(同一线程)。例如,在我正在做的教程中,我将 Instrument class(模型)的 NotifyConnected 信号连接到 'this' 的 onConnected 插槽,也就是视图管理器,请参阅 SetupViewManager::WireButtons (), 代码第三行。 (我正在使用 MVVM 设计模式)。这里的信号和槽是有意义的,因为 Instruments class(模型)不应该知道任何关于视图管理器的信息。 (即将视图管理器的引用传递给模型是不行的,因为它会破坏 MVVM 设计模式。)太棒了。

我遇到的问题是,接下来在本教程中,ViewManager 的 onConnected 插槽会发出其他信号,然后我必须继续手动连接到另一个视图 class 的插槽,即 SetupTab(ref void SetupViewManager::onConnected 和代码中的 void SetupViewManager::WireDisplayUpdate())。

我的问题是,为什么不直接调用 SetupTab 的方法来替换 onConnected 插槽中的所有发射?对我来说感觉像是过于复杂的代码。

付出额外的努力来发出信号并且必须将所有东西连接起来只是为了简单地从另一个 class 调用一个 public 函数(信号)有什么好处,我有一个参考?它不是多线程应用程序(我知道信号和插槽是线程安全的)。

请赐教

谢谢。

setupviewmanager.cpp:

#include "setupviewmanager.h"
#include "View/setuptab.h"
#include "Model/instrument.h"
#include "Model/settings.h"
#include "utils.h"

namespace Ps
{
    SetupViewManager::SetupViewManager(QObject *parent,
                                       SetupTab &tab,
                                       Instrument &inst,
                                       Settings &config) :
        QObject(parent),
        m_setupTab(tab),
        m_instrument(inst)
    {
        WireSettings(config);
        config.ParseJsonData();
        WireHostAndPort();
        WireMessages();
        WireButtons();
        WireDisplayUpdate();

        m_setupTab.SetHostName(config.getHostName());
        m_setupTab.SetPort(config.getPortNumber());
        m_setupTab.SetCommands(config.getCommandsAsModel());
        auto long_wait = config.getLongWaitMs();
        auto short_wait = config.getShortWaitMs();
        m_instrument.SetlongWaitMs(long_wait);
        m_instrument.SetShortWaitMs(short_wait);
        emit NotifyStatusUpdated(tr("Long wait Ms: %1").arg(long_wait));
        emit NotifyStatusUpdated(tr("Short Wait Ms: %1").arg(short_wait));
        onDisconnected();
    }

    SetupViewManager::~SetupViewManager()
    {
        Utils::DestructorMsg(this);
    }

    void SetupViewManager::WireSettings(Settings &config)
    {
        connect(&config, &Settings::NotifyStatusMessage, &m_setupTab, &SetupTab::onStatusUpdated);
    }

    void SetupViewManager::WireHostAndPort()
    {
        connect(&m_setupTab, &SetupTab::NotifyHostNameChanged, &m_instrument, &Instrument::onHostNameChanged);
        connect(&m_setupTab, &SetupTab::NotifyPortChanged, &m_instrument, &Instrument::onPortChanged);
    }

    void SetupViewManager::WireMessages()
    {
        connect(&m_instrument, &Instrument::NotifyErrorDetected, &m_setupTab, &SetupTab::onStatusUpdated);
        connect(&m_instrument, &Instrument::NotifyStatusUpdated, &m_setupTab, &SetupTab::onStatusUpdated);
        connect(this, &SetupViewManager::NotifyStatusUpdated, &m_setupTab, &SetupTab::onStatusUpdated);
    }

    void SetupViewManager::WireButtons()
    {
        connect(&m_setupTab, &SetupTab::NotifyConnectClicked,&m_instrument, &Instrument::Connect);
        connect(&m_instrument, &Instrument::NotifyConnected, &m_setupTab, &SetupTab::onConnected);
        connect(&m_instrument, &Instrument::NotifyConnected, this, &SetupViewManager::onConnected);

        connect(&m_setupTab, &SetupTab::NotifyDisconnectClicked,&m_instrument, &Instrument::Disconnect);
        connect(&m_instrument, &Instrument::NotifyDisconnected, &m_setupTab,&SetupTab::onDisconnected);
        connect(&m_instrument, &Instrument::NotifyDisconnected, this, &SetupViewManager::onDisconnected);

        connect(&m_setupTab, &SetupTab::NotifySendClicked,&m_instrument, &Instrument::onSendRequest);
        connect(&m_instrument, &Instrument::NotifyDataSent,&m_setupTab, &SetupTab::onDataSent);

        connect(&m_setupTab, &SetupTab::NotifyReceiveClicked,&m_instrument, &Instrument::onReceiveRequest);
        connect(&m_instrument, &Instrument::NotifyDataReceived,&m_setupTab, &SetupTab::onDataReceived);
    }

    void SetupViewManager::WireDisplayUpdate()
    {
       connect (this, &SetupViewManager::NotifyConnectEnabled, &m_setupTab, &SetupTab::onConnectEnabled);
       connect (this, &SetupViewManager::NotifyDisconnectEnabled, &m_setupTab, &SetupTab::onDisconnectEnabled);
       connect (this, &SetupViewManager::NotifyDirectCommandsEnabled, &m_setupTab, &SetupTab::onDirectCommandsEnabled);
       connect (this, &SetupViewManager::NotifyControlTabEnabled, &m_setupTab, &SetupTab::onControlTabEnabled);
    }

    void SetupViewManager::onConnected()
    {
        emit NotifyConnectEnabled(false); // HERE. Why not just call method directly with m_setupTab.onConnectEnabled(false); etc...?
        emit NotifyDisconnectEnabled(true);
        emit NotifyDirectCommandsEnabled(true);
        emit NotifyControlTabEnabled(true);
    }

    void SetupViewManager::onDisconnected()
    {
        emit NotifyConnectEnabled(true);
        emit NotifyDisconnectEnabled(false);
        emit NotifyDirectCommandsEnabled(false);
        emit NotifyControlTabEnabled(false);
    }
}

信号槽机制的优点:

  • 当您的 class 没有关于其客户的信息时易于使用;
  • 可用于线程安全调用;
  • 你不能手动记住所有的对象来通知他们;
  • 连接两个对象的唯一规则是它们都必须是 QObject subclasses。

缺点:

  • 较慢的调用(每个信号发出所有连接对象的扫描列表);
  • 可能是复杂的意大利面条代码;你不知道,谁和什么时候会调用任何插槽,或者谁会收到发射信号。

您应该考虑一下自己的情况。如果 SetupViewManager 外部没有信号 "listeners",请尝试直接调用。如果其他人可以连接到此信号,则您的选择是发出它们。

使用信号可能还有其他原因。但是没有理由仅仅为了调用函数而使用它们。至少在一个线程中。

信号和槽用于解耦 classes,这样它们就不需要明确知道谁使用它们的功能以及如何使用它们。在许多情况下,解耦是软件设计的理想特征。当然,它本身并不是目的,当它帮助您推理代码的正确性并使其更易于维护时,它很有用。解耦有助于 understanding/reasoning 代码,因为它会导致更小的代码单元,您可以单独分析这些代码。另一种看待它的方式是关注点分离:让一个代码单元做一件事,例如将一个 class 集中在功能的一个方面。

当你有一对 classes 并想决定是否将它们配对时,请考虑它们是否可以与其他 classes 一起使用。 A 可以耦合到 B,但是 C 而非 B 可以使用耦合这对的接口吗?如果是这样,那么必须使用一些解耦模式,信号槽模式就是其中之一。

例如,让我们比较一下这两个接口如何影响与用户代码的耦合。 objective 很简单:将调试输出添加到对象的析构函数:

class QObject {
  ...
  Q_SIGNAL void destroyed(QObject * obj = Q_NULLPTR);
};

class QObjectB {
  ...
  virtual void on_destroyed();
};

int main() {
  QObject a;
  struct ObjectB : QObjectB {
    void on_destroyed() override { qDebug() << "~QObjectB"; }
  } b;
  QObject::connect(&a, &QObject::on_destroyed, []{ qDebug() << "~QObject"; });
}

信号槽接口允许您轻松地向现有对象添加功能,而无需子class它们。它是 Observer pattern 的一个特别灵活的实现。这将您的代码与对象的代码分离。

第二个实现,使用模板方法相似模式,强制更紧密的耦合:要作用于 ObjectB 的破坏,你必须有一个派生的 class 的实例,你在其中实现所需的功能。