In-depth understanding of the signal slot mechanism (i) (bigger picture, speaking good)

Source: Internet
Author: User

This article comes from A deeper look at signals and Slots,scott Collins 2005.12.19. What we are saying here is that the "signal slot" is not just a signal slot inside the Qt library, but rather a global height that understands the signal slot from a system perspective. So in this article, the Qt signal slot is only introduced as an implementation, we will also introduce another kind of signal slot implementation--boost::signal. Therefore, when you see some of the names of the signals in the article, perhaps just for the sake of the description of convenience and fabricated, actually do not have this signal.

What is a signal slot?

We can answer this question from two angles, one short and the other longer.

Let's first answer the question in the simplest language-what is a signal slot?

    • Signal slot is an implementation of the observer pattern, or a sublimation;
    • A signal is an event that can be observed, or at least a notification that an event has occurred;
    • A slot is an observer, usually the function that is called when the object being observed changes-or when the signal is emitted;
    • You can connect signals and slots to form an observer-the relationship of the observed;
    • The signal is emitted when the event or state changes, and the signal issuer is obliged to call all registered functions (slots) that are interested in the event (signal).

Signals and slots are many-to-many relationships. One signal can be connected to multiple slots, and one slot can also monitor multiple signals.

The signal can have additional information. For example, a windowclosing signal may be emitted when the window is closed, and the signal can contain a handle to the window to indicate which window is emitting the signal, and a slider may emit a signal when sliding, which contains the specific position of the slider, or the new value, and so on. We can interpret the signal slots as function signatures. Signals can only be connected with slots with the same signature. You can think of a signal as the name of an image of the underlying event. Like this windowclosing signal, we know this is what happens when a window close event occurs.

Signal slots are actually language-independent, there are many ways to achieve the signal slot, different implementation mechanism will lead to a large number of signal slots. The term signal slot was originally from the Trolltech Company's Qt library (which has now been acquired by Nokia). In 1994, the first version of Qt was released, bringing us the concept of a signal slot. This concept immediately aroused the attention of computer science, and put forward a variety of different implementations. Today, the signal slots are still one of the core of the Qt library, and many other libraries provide similar implementations, and there are even a number of libraries that specialize in providing this mechanism.

After a brief understanding of the signal slot, let's answer the question from another angle: what is a signal slot? Where do they come from?

We have already learned about the concept of signal slot correlation. Here's a more detailed look at how the signal slot mechanism is evolving and how to use it in your own code.

A very important part of programming is component interaction: part of the system needs to tell the other part to do some things. Let's start with a simple example:

C++class button{public:    void clicked ();//something that happens:buttons could be clicked};class page{public:    V OID Reload (); ... which I might want to does when a Button is clicked};

In other words, the page class knows how to reload the pages (reload), and the Button has an action that is clicked (click). Suppose we have a function that returns the current page CurrentPage (), then the current page should be re-loaded when the button is clicked.

C + +---Making the connection directlyvoid button::clicked () {    currentpage ()->reload ();//Buttons know exactly W Hat to does when clicked}

It doesn't look very good. Because the Button's class name seems to imply that this is a reusable class, the click operation of this class is tightly coupled with the Page. This allows the reload () function of currentpage () to be called as soon as the button is clicked. This cannot be reused at all, perhaps by changing it to the name Pagereloadbutton better.

In fact, it has to be said that this is indeed a way of realization. If the Button::click () function is virtual, then you can write a new class to inherit the Button:

C + +---Connecting to different actions by Specializingclass Button{public:    virtual void clicked () = 0;//Buttons There is no idea, what, when Clicked};class pagereloadbutton:public button{public:    virtual void clicked () {        Curr Entpage ()->reload ();    ... specialize Button to connect it to a specific action    }};

OK, now the Button can be reused. But that's not a good solution.

Introducing Callbacks

Let's stop and think about how we can solve this problem in the era of only C. If only C, there is no such thing as virtual. There are many ways to reuse, but without the help of classes, we take another solution: function pointers.

/* C---Connecting to different actions via function pointers */void reloadpage_action (void*)/* One possible action wh En a Button is clicked */{    reloadpage (CurrentPage ());} void loadpage_action (void* URL)/* Another possible action when a Button is clicked */{    loadPage (CurrentPage (), (cha r*) URL);} struct Button {/    * ... now I keep a (changeable) pointer to the function to be called */    Void (*ACTIONFUNC_) (); 
   
    void* Actionfuncdata_;}; void buttonclicked (button* button) {/    * Call the attached function, whatever it might is *    /if (Button && ; BUTTON->ACTIONFUNC_)        (*button->actionfunc_) (Button->actionfuncdata_);}
   

This is what is often called a "callback". The buttonclicked () function does not know which function to invoke at compile time. The function that is called is passed in at run time. In this way, our Button can be reused because we can pass different function pointers at runtime to get a different click action.

Increase type safety

For C + + or Java programmers, this is not always a preference. Because this is not type-safe (note that the URL has a step-forcing type conversion).

Why do we need type safety? The type of an object actually implies how you will use the object. With a clear object type, you can let the compiler help you check that your code is being used correctly, as if you had drawn a boundary and told the compiler that if someone crosses the line, you will get an error. However, without type safety, you will lose this advantage and the compiler will not be able to help you with this maintenance. It's like you're driving. As long as you have enough speed, you can make your car fly, but, in general, this speed will remind you that it is too insecure. There will also be some devices, such as radar, that will always help you check the situation. This is as the compiler helps us do, and it is within the scope of a safe use of our bath.

Come back and look at our code. Using C is not type-safe, but using C + +, we can put callback function pointers and data inside a class to gain the benefits of type safety. For example:

//re-usable actions, C + + style (Callback objects) class Abstractaction{public:virtual void execute () = 0;//sub-  Classes re-implement this to actually do something};class button{//... now I keep a (changeable) pointer to the action To be executed abstractaction* action_;}; void button::clicked () {//execute the attached action, whatever it may if (Action_) Action_->execute ();} Class Pagereloadaction:public AbstractAction//One possible action when a Button is clicked{public:virtual void    Execute () {currentpage ()->reload ();    }};class pageloadaction:public abstractaction//Another possible action when a Button is clicked{public://...    virtual void execute () {currentpage ()->load (URL_); }private:std::string Url_;}; 

All right! Our Button has been easily reused and is type-safe, with no forced type conversions. This implementation has been able to solve most of the problems encountered in the system. It seems that the current solution is similar to the previous one, inheriting a class. But now we have an abstraction of the action, which was previously an abstraction of the Button. This is much like the implementation of the previous C, where we associate different actions with the Button. Now, we're going to find a more satisfying approach.

http://blog.csdn.net/devbean/article/details/5998558

In-depth understanding of the signal slot mechanism (i) (bigger picture, speaking good)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.