Design pattern Observer (Observer) pattern and its C + + general implementation (next)

Source: Internet
Author: User
Tags event listener

We give a general observer pattern skeleton in the C + + language in the article "Design pattern Observer (Observer) mode and its C + + general implementation (middle)". However, the actual project needs are often more complex than the ideal state, this is to explore with the reader in the real world may encounter a variety of difficult problems and solutions.

I have listed the problems I have encountered so far as follows:

Composite theme

Multithreading

Updating the Observer list by modifying the method

Let's talk about it all at once.

(i) Composite theme

Considering the component design of the GUI, I am accustomed to representing it with the Widget class, which involves many user interactions and system events, the most common user interaction events being mouse and keyboard events. If the architect decides to design the entire UI frame as an event listener, then the widget has the role of the subject, and the corresponding mouse and keyboard events are the observer roles. In fact, it is common for a subject to have multiple (not multiple) observers.

We use the observer pattern skeleton given by medium to implement this type of application.

With multiple inheritance mechanisms, it's easy to do:

01.struct MouseListener {
void mousemoved (int x, int y) {}
03.};
04.
05.struct KeyListener {
keypressed void (int keycode) {}
07.};
08.
09.class widget:public Basicsubject<mouselistener>, public basicsubject<keylistener>{...};

The pseudo code to add an event listener is roughly as follows:

01.MouseListener Mel;
02.KeyListener Kel;
03.Widget W;
04.w.addobserver (MEL);
05.w.addobserver (Kel);

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.