Key Words: Observer pattern in C++
Topics at a glance:
- Let us observe a subject closely
- how we can improvise our Document editor application with observer pattern
- Document editor application is now 2.0 !
In previous chapter we saw command behavioral pattern. In this chapter we will improvise our Application – Document editor using Observer pattern.
Observer pattern in C++
Observer in simple terms is a contract between two entities called Subject and Observer. Its core philosophy is created on a subscription-based notification model, where the observers are the subscribers who are interested in the changes happening in a subject.
In the Document editor, you might have seen that whenever a document is closed, it will notify the application. But in the previous version presented in Chapter 13, I used basic object pointer (pointer to Application) and a function call back using member function pointer. The purpose was to notify the application about a document close. What all things to do when the subscriber receives such a notification depends on the use-case. Say in our Application class, Application can prompt the user to re-open the closed document or open another new document for editing and so on.
This use-case where observers are notified by the subject about any of its specific updates could be generalized and designed with the help of Observer Design pattern. So, here we are making subjects and its observers as objects. Subject instances must implement the interfaces such as notify(), attach(Observer *) and detach(Observer *) , while the Observer instances must implement the interface update(current_state val). This is like a contract between the subject and the observers and unlike chapter 13’s implementation of a similar functionality, here we can subscribe, unsubscribe and get updates. Also, in Observer pattern we build this framework on top of object instances rather than isolated call back functions.
Now, let us see how we can improvise our Document editor application with the help of Observer pattern. Here the Observer is Application instance and is interested only when, the state of it subject i.e. Document instance changes to closed. When Application instance is notified about a document close, it prompts the user to open a new document.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | #include <iostream> #include <string> #include <memory> #include <vector> using namespace std; class Command { public: virtual ~Command(){} virtual void execute() = 0; }; class Menu_Item { private: unique_ptr<Command> command_object_; string name_; public: Menu_Item(const char* const name) : name_{name}, command_object_{nullptr} { } ~Menu_Item() { cout << "Menu_Item : " << name_ << " destroyed" << endl; command_object_.reset(); } void add_command_object(Command *command_object) { command_object_.reset(command_object); } int click() { int status = -1; if(command_object_ != nullptr) { command_object_->execute(); status = 0; } return status; } string& get_name() { return name_; } }; class Menu { private: string name_; vector<unique_ptr<Menu_Item>> menu_items; public: Menu(const char* const name): name_{name} { } ~Menu() { cout << "Menu " << name_ << " destroyed" << endl; for (auto &item : menu_items) { item.reset(); } } void add_menu_item(unique_ptr<Menu_Item> menu_item) { menu_items.push_back(std::move(menu_item)); } int hover() { int choice; int count = 0; for (auto &item : menu_items) { cout << item->get_name() << " : " << count++ << endl; } cout << "Enter your Menu Item choice : "; cin >> choice; if( (choice >= 0) &&(choice <= menu_items.size()) ) { return menu_items[choice]->click(); } } // overloaded version // used for mimicking a menu item click by the application int hover(int choice) { return menu_items[choice]->click(); } string& get_name() { return name_; } }; class Subject; enum class doc_states{created = 0, opened, closed, changed, moved}; class Observer { public: ~Observer(){} virtual void update(doc_states current_state) = 0; }; class Subject { public: ~Subject(){} virtual void notify() = 0; virtual void attach(Observer *this_observer) = 0; virtual void dettach(Observer *this_observer) = 0; }; class Document : public Subject { private: string name_; doc_states current_state; vector<Observer*> observers; public: typedef void (Document::*doc_function)(); Document(): current_state{doc_states::created} { /* do nothing */ } ~Document() { if( (current_state != doc_states::closed) &&(current_state != doc_states::created) ) { // i.e. a document is open. So close it. close(); } } void open() { cout << "Enter the file name to open" << endl; cin >> name_; current_state = doc_states::opened; cout << "Document : " << name_ << " is open" << endl; } void close() { if( (current_state != doc_states::closed) &&(current_state != doc_states::created) ) { current_state = doc_states::closed; cout << "Document : " << name_ << " is closed" << endl; name_.clear(); // notify the subscribed observers notify(); } else { cout << "No documents are open" << endl; } } //void copy(int start, int end, string &copied_text) void copy() { if(current_state != doc_states::closed) { cout << "copying..." << endl; // copy from start to end to copied_text cout << "copy complete" << endl; } else { cout << "No documents are open" << endl; } } //void paste(int position, string& insert_text) void paste() { if(current_state != doc_states::closed) { cout << "pasting..." << endl; cout << "pasting complete" << endl; } else { cout << "No documents are open" << endl; } } //void cut(int start, int end, string &extracted_text) void cut() { if(current_state != doc_states::closed) { cout << "cutting..." << endl; // copy from start to end to copied_text cout << "cut complete" << endl; } else { cout << "No documents are open" << endl; } } // support for Observer pattern void notify() override { for( auto &observer : observers ) { observer->update(current_state); } } void attach(Observer *this_observer) override { observers.push_back(this_observer); } void dettach(Observer *this_observer) override { int position = 0; auto begin = observers.begin(); auto end = observers.end(); for( auto itr = begin; itr < end; ++itr ) { auto obs = *itr; if(this_observer == obs) { observers.erase(itr); } } } }; class Open_Document_Command : public Command { private: shared_ptr<Document> document_; Document::doc_function function; public: Open_Document_Command(shared_ptr<Document> document, Document::doc_function call_back): document_{document}, function{call_back} { } void execute() override { (document_.get()->*function)(); } }; class Close_Document_Command : public Command { private: shared_ptr<Document> document_; Document::doc_function function; public: Close_Document_Command(shared_ptr<Document> document, Document::doc_function call_back): document_{document}, function{call_back} { } void execute() override { (document_.get()->*function)(); } }; class Copy_Document_Command : public Command { private: shared_ptr<Document> document_; Document::doc_function function; public: Copy_Document_Command(shared_ptr<Document> document, Document::doc_function call_back): document_{document}, function{call_back} { } void execute() override { (document_.get()->*function)(); } }; class Paste_Document_Command : public Command { private: shared_ptr<Document> document_; Document::doc_function function; public: Paste_Document_Command(shared_ptr<Document> document, Document::doc_function call_back): document_{document}, function{call_back} { } void execute() override { (document_.get()->*function)(); } }; class Cut_Document_Command : public Command { private: shared_ptr<Document> document_; Document::doc_function function; public: Cut_Document_Command(shared_ptr<Document> document, Document::doc_function call_back): document_{document}, function{call_back} { } void execute() override { (document_.get()->*function)(); } }; class Application : public Observer { private: vector<unique_ptr<Menu>> menus; shared_ptr<Document> current_doc; enum class signal{app_launched = 0, app_exit, user_interrupt, other, no_trigger}; signal trigger; void prompt_to_open_new_document() { // prompt the user cout << "Open a document for editing" << endl; return; } public: Application() { string doc_name; trigger = signal::app_launched; cout << "Document Editor App, Version : 2.0" << endl; shared_ptr<Document> document = make_shared<Document>(); current_doc = document; // Attach this 'Application' as an Observer of document (document.get())->attach(this); // 2. add Menus "File" and "Edit" unique_ptr<Menu> file_menu = make_unique<Menu>("File"); unique_ptr<Menu_Item> open_item = make_unique<Menu_Item>("Open"); Open_Document_Command *open_cmd_object = new Open_Document_Command(document, &Document::open); open_item->add_command_object(open_cmd_object); file_menu->add_menu_item(std::move(open_item)); unique_ptr<Menu_Item> close_item = make_unique<Menu_Item> ("Close"); Close_Document_Command *close_cmd_object = new Close_Document_Command(document, &Document::close); close_item->add_command_object(close_cmd_object); file_menu->add_menu_item(std::move(close_item)); unique_ptr<Menu> edit_menu = make_unique<Menu>("Edit"); unique_ptr<Menu_Item> copy_item = make_unique<Menu_Item>("Copy"); Copy_Document_Command *copy_cmd_object = new Copy_Document_Command(document, &Document::copy); copy_item->add_command_object(copy_cmd_object); edit_menu->add_menu_item(std::move(copy_item)); unique_ptr<Menu_Item> paste_item = make_unique<Menu_Item>("Paste"); Paste_Document_Command *paste_cmd_object = new Paste_Document_Command(document, &Document::paste); paste_item->add_command_object(paste_cmd_object); edit_menu->add_menu_item(std::move(paste_item)); unique_ptr<Menu_Item> cut_item = make_unique<Menu_Item>("Cut"); Cut_Document_Command *cut_cmd_object = new Cut_Document_Command(document, &Document::cut); cut_item->add_command_object(cut_cmd_object); edit_menu->add_menu_item(std::move(cut_item)); menus.push_back(std::move(file_menu)); menus.push_back(std::move(edit_menu)); } int select_menu() { int choice = 0; int end_app = 0; cout << "Enter your Menu choice" << endl; for(auto &menu : menus) { cout << menu->get_name() << " : " << choice++ << endl; } end_app = choice; cout << "Exit : " << end_app << endl; cin >> choice; if( (choice >= 0) &&(choice < menus.size())) { menus[choice]->hover(); } else if(choice == end_app) { // set the trigger trigger = signal::app_exit; end_application(); return 1; } return 0; } // To support Observer pattern void update(doc_states current_state) { cout << "Application : document close() detected" << endl; switch(current_state) { case (doc_states::closed): { // open new document for editing by prompting the user if(trigger != signal::app_exit) { prompt_to_open_new_document(); } break; } default: { // do nothing break; } } return; } void end_application() { // do clean up // release back the memory resources to free store for(auto &menu : menus) { menu.reset(); } // close the current_doc current_doc.reset(); cout << "Application exiting..." << endl; return; } ~Application() { cout << "Inside Application destructor" << endl; } }; int main() { Application new_app; int end_app = 0; while(end_app == 0) { end_app = new_app.select_menu(); } cout << "Main Ends" << endl; } |
Want to see this code in action?
Document Editor App, Version : 2.0
Enter your Menu choice
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your Menu Item choice : 0
Enter the file name to open
hello
Document : hello is open
Enter your Menu choice
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your Menu Item choice : 1
Document : hello is closed
Application : document close() detected
Open a document for editing
Enter your Menu choice
File : 0
Edit : 1
Exit : 2
2
Menu File destroyed
Menu_Item : Open destroyed
Menu_Item : Close destroyed
Menu Edit destroyed
Menu_Item : Copy destroyed
Menu_Item : Paste destroyed
Menu_Item : Cut destroyed
Application exiting...
Main Ends
Inside Application destructor
Observer in action:
Here you can see that when the User choose to close the document, application gets notified and prompts the user to open a file to edit. Finally, when User chooses to exit, Application does the clean-up as usual.
Other improvisations.
This document editor app (version 2.0) also fixed the issue with user selecting an operation when no documents are open or try to close a document which is not open. Want to see these features?
Document Editor App, Version : 2.0
Enter your Menu choice
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your Menu Item choice : 1
No documents are open
Enter your Menu choice
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your Menu Item choice : 0
Enter the file name to open
hello
Document : hello is open
Enter your Menu choice
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your Menu Item choice : 1
Document : hello is closed
Application : document close() detected
Open a document for editing
Enter your Menu choice
File : 0
Edit : 1
Exit : 2
1
Copy : 0
Paste : 1
Cut : 2
Enter your Menu Item choice : 0
No documents are open
Enter your Menu choice
File : 0
Edit : 1
Exit : 2
2
Menu File destroyed
Menu_Item : Open destroyed
Menu_Item : Close destroyed
Menu Edit destroyed
Menu_Item : Copy destroyed
Menu_Item : Paste destroyed
Menu_Item : Cut destroyed
Application exiting...
Main Ends
Inside Application destructor
You can see that the Application tells the User that “No documents are open” when any operation is invoked when no document is already open.
Enjoyed the chapter. Let me know in the comments below. Thanks 🙂