There is an entity document (Document class), in which there may be changes associated with the font, text, size, etc., etc., etc., etc., etc.
This entity has a strong desire to signal these changes to outside listeners. But she (our essence) does not want to know too much about who she communicates with. Our document only wants to be heard using a special protocol (read the interface). Yes, this pattern begets egoists!
Let's say this (this is a protocol for communicating with listeners):
class AbstractDocumentChangedListener { public: virtual void fontSizeChanged(int was, int current) =0; virtual void fontNameChanged(string was, string current) =0; virtual void textChanged(string was, string current) =0; }
Having such a protocol we can register a listener in the list of listeners inside the object of our document:
class Document { public: //... void addListener(AbstractDocumentChangedListener* listener) { _listeners.insert(listener); } //... private: set<AbstractDocumentChangedListener*> _listeners; }
Now everyone who wants to know what is happening with our document there should implement the corresponding interface:
class DocumentListener : public AbstractDocumentChangedListener { public: void fontSizeChanged(int was, int current) override { //Теперь я знаю, что "они" изменили размер шрифта } void fontNameChanged(string was, string current) override { //Теперь я знаю, что "они" выбрали другой шрифт } void textChanged(string was, string current) override { // Другой текст? Хм, странно ) } }
And if I need not all the methods of this protocol?
class SomeDocumentChangedListener : public AbstractDocumentChangedListener { public: void fontSizeChanged(int was, int current) {}; void fontNameChanged(string was, string current) {}; void textChanged(string was, string current) {}; }
And then:
class DocumentListener : public SomeDocumentChangedListener { public: void textChanged(string was, string current) { //... } }
In any case, the registration of the listener in the target object will be as follows:
//... Document doc; DocumentListener listener; doc.addListener(&listener); //...
In this way, this pattern is implemented very widely and is often used in Java. It can also be used in pure C ++.
In Qt, this principle is implemented through the signals / slots system. Entities signal their internal changes with the help of emit, and, accordingly, students receive these changes with the help of slots implementation, respectively, establishing a connection between them (connect).