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);