GTK,Qt事件触发机制

143 阅读2分钟

GTK

GTK和Qt采用松耦合的方式,进行事件触发

松耦合(Loose Coupling)是一种软件设计原则,旨在减少系统中各个组件之间的依赖关系。通过实现松耦合,系统的各个部分可以独立地进行开发、测试和维护,从而提高系统的灵活性和可扩展性。

实现松耦合的方式

  1. 接口和抽象:使用接口或抽象类来定义组件之间的交互,而不是直接依赖具体的实现。这使得不同的实现可以互换。
  2. 事件驱动:使用事件或信号-槽机制(如在 Qt 中)来处理组件之间的通信。发出事件的组件不需要知道谁在监听这些事件。
  3. 依赖注入:通过依赖注入(Dependency Injection)模式,将组件的依赖关系外部化,使得组件不需要自己创建依赖对象,而是通过构造函数或方法参数传入。
  4. 消息队列:使用消息队列或发布-订阅模式来解耦组件之间的通信。组件可以发布消息而不需要知道谁在接收这些消息。

示例

展示如何通过接口实现松耦合:

// 定义一个接口
class INotification {
public:
    virtual void notify(const std::string &message) = 0;
};

// 实现接口的具体类
class EmailNotification : public INotification {
public:
    void notify(const std::string &message) override {
        // 发送电子邮件通知
        std::cout << "Email: " << message << std::endl;
    }
};

class SMSNotification : public INotification {
public:
    void notify(const std::string &message) override {
        // 发送短信通知
        std::cout << "SMS: " << message << std::endl;
    }
};

// 使用依赖注入
class NotificationService {
private:
    INotification *notification;

public:
    NotificationService(INotification *notification) : notification(notification) {}

    void sendNotification(const std::string &message) {
        notification->notify(message);
    }
};

// 主函数
int main() {
    EmailNotification email;
    SMSNotification sms;

    NotificationService service(&email);
    service.sendNotification("Hello via Email!");

    NotificationService service2(&sms);
    service2.sendNotification("Hello via SMS!");

    return 0;
}

在这个示例中,NotificationService 类依赖于 INotification 接口,而不是具体的通知实现(如 EmailNotificationSMSNotification)。这使得 NotificationService 可以与任何实现了 INotification 接口的类一起工作,从而实现了松耦合。

这个示例向我们展示了基本的实现方式: 接下来以GTK为核心,看看GTK原理

android的实现方式是将事件的监听回调作为对象的方法,当我们触 发后,事件通过viewTree,回调这个方法。

Button btn = new Button();
btn.setOnClickListener(v->{
    if(v != null){
        //回调函数实现
    }
});

而GTK事件触发是独立于View之外的,通过发送一个信号,在发送信号的时候将回调函数绑定在当前view:

int main(){
    // 创建一个按钮
    button = gtk_button_new_with_label("点击我");
    g_signal_connect(button, "clicked", G_CALLBACK(on_button_clicked), NULL);
    return 0;
}

// 按钮点击事件处理函数
static void on_button_clicked(GtkWidget *widget, gpointer data) {
    g_print("按钮被点击了!\n");
}

g_signal_connect原理: