Key Words: Strategy design pattern
Topics at a glance:
- Let us strategize before action
- Document Editor App is now version 4.0!
Strategy design pattern
In this chapter we will see another behavioral pattern called the strategy pattern. Strategy helps you to encapsulate algorithms inside object instances of a base-class-derived-class system. It exposes only a minimal interface to configure/rather select the algorithm required. This portion is called selecting the strategy. Once the user selects the strategy, the algorithm applicable to that context will run and gives the result. User will code to a base class instance without even knowing which derived class instance is implementing the algorithm. Varying implementations of a family of algorithms will be encapsulated within each of the derived classes. Base class delegates specific implementation of algorithms to it’s derived classes.
For explaining strategy, I am taking our Document Application as an example. Till version 3.0, our Document application is just an application framework with basic elements for user interaction such as menus and menu items. It does not actually read or write any files. So, let us make this document editor a real document editor which can open real files for reading or writing.
Let us see the role of strategy design pattern in this context. When User selects an option to edit the document, he will be prompted with the basic formatting options such as ‘width’ of the document and ‘alignment‘ type. User can select align to ‘left’ or ‘right’. Now, the Document class can use these user inputs to select the formatting strategy and delegates this to an object instance of a specific formatter sub-class. Strategy pattern is used to design, the formatter class. Formatter is our base class. Formatter can read the lines from user/console. For aligning purposes, it has to seek help of its derived class instances. i.e. Formatter class only declares a pure virtual align() member function. Derived classes ‘align_left_formatter’ and ‘align_right_formatter’ implements the actual algorithm (strategy) for left and right alignment, respectively.
That is the philosophy of strategy pattern. i.e. to encapsulate a family of (related) algorithm implementations in derived classes.
The client will program to an abstract base class and select the algorithm or the way the client is expecting the result. Here, client program is the Document class itself which handles the files.
The client does the following:
1. It opens the file through a fstream object based on the user inputs.
2. It selects a strategy based on user inputs.
3. It creates an object instance of a specific formatter sub-class based upon the selected strategy.
4. It then uses this object instance to make the necessary formatting on the open file.
That said, formatter does not take care of opening and closing files. It just expects the client to give a valid file handle for a file stream opened in the appropriate mode (read, write, append, truncate etc.).
NOTE : Use manipulators defined in ‘iomanip‘ header files for opening the file stream in the required mode.
Let us now see our Strategy Pattern i.e. formatter class in action:
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 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 | #include <iostream> #include <string> #include <memory> #include <vector> #include <fstream> #include <iomanip> using namespace std; class formatter { public: virtual ~formatter(){} void format(fstream &output_file) { string line; cout << "Start entering your text" << endl; cout << "Enter 'END' for ending the session" << endl; while(output_file) { getline(cin, line); if(line.compare("END") == 0) { break; } align(line); output_file << line << endl; line[0] = '\0'; } } private: virtual void align(string &) = 0; }; class align_right_formatter : public formatter { private: int width_; public: align_right_formatter(int width = 20) : width_{width} { } private: void align(string & line) override { int len = line.length(); const string space = " "; const string new_line = "\n"; vector <string> line_lets; int rem_len = len; int pos = 0; int count = 1; int offset = 0; int org = 0; if(rem_len <= width_) { line_lets.push_back(line); } while(rem_len > width_) { offset = width_ * count; while(true) { if(line[offset] == ' ') { if(offset - org <= width_) { break; } else if (offset - 1 < 0) { break; } // The string is still lengthy // can't break here } --offset; } line.insert(offset, new_line); len = line.length(); rem_len = (len - offset) + 1; org = len - rem_len; count++; } stringstream ss(line); string tmp; while(getline(ss, tmp, '\n')) { line_lets.push_back(tmp); } line.clear(); for(auto str : line_lets) { int limit = width_ - str.length() - 1; for(int i = 0; i < limit; ++i) { str.insert(i, space); } line.append(str); line.append(new_line); } return; } }; class align_left_formatter : public formatter { private: int width_; public: align_left_formatter(int width = 20) : width_{width} { // do nothing } private: void align(string & line) override { int count = 1; int offset = 0; int len = line.length(); const string new_line{"\n"}; int rem_len = len; int org = 0; while(rem_len >= width_) { offset = width_ * count; while(true) { if(line[offset] == ' ') { if(offset - org <= width_) { break; } else if (offset - 1 < 0) { break; } // The string is still lengthy // can't break here } --offset; } line.insert(offset + 1, new_line); len = line.length(); rem_len = (len - offset) + 1; org = len - rem_len; count++; } return; } }; class Command { public: virtual ~Command(){} virtual void execute() = 0; }; class Selectable { public: virtual ~Selectable(){} virtual string get_name() = 0; virtual void select() = 0; }; class Menu_Item : public Selectable { private: string name_; unique_ptr<Command> command_object_; 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); } void select() override { click(); } int click() { int status = -1; if(command_object_ != nullptr) { command_object_->execute(); status = 0; } return status; } string get_name() { return name_; } }; class Menu : public Selectable { private: string name_; vector<unique_ptr<Selectable>> 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<Selectable> menu_item) { menu_items.push_back(std::move(menu_item)); } void select() override { hover(); } void hover() { int choice; int count = 0; for (auto &item : menu_items) { cout << item->get_name() << " : " << count++ << endl; } cout << "Enter your choice : "; cin >> choice; if( (choice >= 0) &&(choice <= menu_items.size()) ) { menu_items[choice]->select(); return; } } 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; fstream file; 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_read() { cout << "Enter the file name to open for reading" << endl; cin >> name_; file.open(name_, ios::in); // read only mode if(file) { current_state = doc_states::opened; cout << "Document : " << name_ << " is open for reading!\n" << endl; string line; while(file >> line) { cout << line << endl; } cout << "\nEnd of File!" << endl; } } void open_write() { cout << "Enter the file name to open for writing" << endl; cin >> name_; file.open(name_, ios::app); // write in append mode formatter *frmtr = nullptr; if(file) { file << "\n" << endl; current_state = doc_states::opened; cout << "Document : " << name_ << " is open for writing" << endl; // start writing cout << "Select alignment : Left(0), Right(1)" << endl; int alignment_selected = 0; int width = 0; cin >> alignment_selected; cout << "Select width : " << endl; cin >> width; if( (width < 0) || (width > 30) ) { width = 20; } if(alignment_selected == 1) { // right frmtr = new align_right_formatter(width); } else { // left frmtr = new align_left_formatter(width); } if(frmtr != nullptr) { frmtr->format(file); delete frmtr; } } } void close() { if( (current_state != doc_states::closed) &&(current_state != doc_states::created) ) { file.close(); 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 : 4.0" << endl; shared_ptr<Document> document = make_shared<Document>(); current_doc = document; // Attach this 'Application' as an Observer of document (document.get())->attach(this); // add Menus "File" and "Edit" unique_ptr<Menu> file_menu = make_unique<Menu>("File"); unique_ptr<Menu> open_sub_menu = make_unique<Menu>("Open"); unique_ptr<Menu_Item> open_menu_item_1 = make_unique<Menu_Item>("Open For Read"); unique_ptr<Menu_Item> open_menu_item_2 = make_unique<Menu_Item>("Open For Write"); Open_Document_Command *open_read_cmd_object = new Open_Document_Command(document, &Document::open_read); Open_Document_Command *open_write_cmd_object = new Open_Document_Command(document, &Document::open_write); open_menu_item_1->add_command_object(open_read_cmd_object); open_menu_item_2->add_command_object(open_write_cmd_object); open_sub_menu->add_menu_item(std::move(open_menu_item_1)); open_sub_menu->add_menu_item(std::move(open_menu_item_2)); file_menu->add_menu_item(std::move(open_sub_menu)); 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 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]->select(); } 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; } |
The algorithms implemented for Left and right alignment make sure of two things:
1. The text aligns properly to either left or right based upon the selected strategy.
2. Without breaking in between a word (i.e. it breaks the text into next line only at spaces), it makes sure the portion of text is written to the file within the stipulated line width.
Want to see the result?
Document Editor App, Version : 4.0
Enter your choice :
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your choice : 0
Open For Read : 0
Open For Write : 1
Enter your choice : 1
Enter the file name to open for writing
Hai.txt
Document : Hai.txt is open for writing
Select alignment : Left(0), Right(1)
0
Select width :
20
Start entering your text
Enter 'END' for ending the session
Hai
Hello
How are you? Hope
you are fine!
Good seeing you
:)
END
Enter your choice :
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your choice : 1
Document : Hai.txt is closed
Application : document close() detected
Open a document for editing
Enter your choice :
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your choice : 0
Open For Read : 0
Open For Write : 1
Enter your choice : 0
Enter the file name to open for reading
Hai.txt
Document : Hai.txt is open for reading!
Hai
Hello
How
are
you?
Hope
you
are
fine!
Good
seeing
you
:)
End of File!
Enter your choice :
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your choice : 1
Document : Hai.txt is closed
Application : document close() detected
Open a document for editing
Enter your choice :
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your choice : 0
Open For Read : 0
Open For Write : 1
Enter your choice : 1
Enter the file name to open for writing
Hello.txt
Document : Hello.txt is open for writing
Select alignment : Left(0), Right(1)
0
Select width :
20
Start entering your text
Enter 'END' for ending the session
Hello How are you ? I am fine, Thanks. How are you? Am fine too. Heard that you are working on a book on the philosophy of C and C++ ? How it's going ? It's going well and keeps me engaged. Okay good to hear that. All the best for your endeavor!!!
END
Enter your choice :
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your choice : 1
Document : Hello.txt is closed
Application : document close() detected
Open a document for editing
Enter your choice :
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your choice : 0
Open For Read : 0
Open For Write : 1
Enter your choice : 1
Enter the file name to open for writing
Hello.txt
Document : Hello.txt is open for writing
Select alignment : Left(0), Right(1)
1
Select width :
20
Start entering your text
Enter 'END' for ending the session
I have been pondering about starting a blog on my understanding of the popular programming languages C and C++ for quite some time. I am not a seasoned writer. To be honest with you, I am still a little skeptical to foray into this world of blogging! I always try to understand a thing to it's very core by analyzing it, understand how it works and why it works the way it does. And once I understand these, I will articulate or rather try to teach them to my colleagues and peers. I think, I have got some good experience in that regard.
END
Enter your choice :
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your choice : 1
Document : Hello.txt is closed
Application : document close() detected
Open a document for editing
Enter your choice :
File : 0
Edit : 1
Exit : 2
2
Menu File destroyed
Menu Open destroyed
Menu_Item : Open For Read destroyed
Menu_Item : Open For Write 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
Let us see “Hai.txt” ( left aligned and width 20 characters per line )

Now, Let us see the left aligned portion of text saved in “Hello.txt ( width 20 characters per line selected )

Now, see the right aligned portion of text in “Hello.txt” ( width 20 characters per line selected )

Note: The image above is truncated at line 49 due to space limitations. Please visit my GitHub page to see the full text in ‘Hello.txt’ file
Document class and it’s open_read and open_write member functions is the client here. Through the user inputs it selects the strategy and decides either to create instance of ‘align_left_formatter’ or ‘align_right_formatter’. Client, invokes the format member function and leave the rest to the strategy pattern.
We don’t have to use std::unique_ptr while creating formatter instances as it’s scope is limited to the functions open_read and open_write. Once the format function returns, the instance is deleted, and resources are freed.
Enjoyed the chapter? Let me know in the comments below. Thanks 🙂