Chapter 15 : Series On Design Patterns – Composite Pattern

Key Words: Composite design pattern in C++

Topics at a glance:

  • Composites, containers and primitives
  • Document Editor Application is now version 3.0

Composite design pattern in C++

In this chapter we will see the use of a particularly important and widely used design pattern – composite design pattern. In this series, it is our first structural design pattern. Also, we will use one for improvising Document Reader Application.

It’s easy to explain composite pattern with a suitable problem scenario. In our Document reader 1.0 and 2.0 versions, we have added instances of menus and menu items. The idea is, a menu will always contain menu items and menu items will always have a click operation that executes one action. But in real applications menus often expands into other menus and not always menu items essentially. The same is applicable for a ‘Table’ containing sub-‘Tables’ – in which, one row of first table itself contains another sub-table with its own rows and columns. Similarly, in operating systems when you open directory it may contain files or other sub-directories. Coming back to our Application – Document editor, If you stick to concrete Menu class instances that can only contain Menu_Items its difficult to tackle this issue. The idea is to make Menu class a composite class. We have to do one more thing. i.e. to make Menu_Items and Menu class as sub-classes/derived classes of an abstract base class called Selectable. Menu class will become a container of instances of this abstract base class – Selectable. The actual instances will be either Menu instances or Menu_Items instances and both of them “is a” Selectable object as well.

Selectable class will have two pure virtual member functions – select() and get_name(). Both Menu and Menu_Items, as they are derived from Selectable must implement these interfaces select() and get_name() in their own ways. Say, Menu’s select will invoke the hover()  method while Menu_Item’s select() will invoke the click() method. The get_name() methods will simply return their associated names.

Whenever user is presented with the options, he selects one of the presented items. Item can be Menu or a Menu_Item. If it’s a Menu, then it will present another list of Selectable items, which could be either a Menu item or a Menu itself, and this goes on. Thus Menu class has become a composite class, and apparently, the primitive is the Menu_Item class. In previous versions, Menu was a container of Menu_Items. But now we uplifted Menu class as a composite which can hold abstract object’s, and manipulate them without worrying whether it’s a primitive ( a menu item ) or a composite type itself ( i.e menu ). That is the advantage of composites. Composite helps in representing containers and their primitive data types as an abstract object. So, when coding to a composite object instance, programmer does not need to worry whether he is coding to a container instance or a primitive instance.

That is the philosophy behind composite pattern. i.e. to abstract container and its primitives.

Here, in our example, Document Editor Application is at version 3.0, with facility to add sub-menus when opening a file. i.e. whether to open in read only mode or write mode. File menu presents with options to Open, Close. Open presents with options – Open for Read, Open for Write.

Let us see version 3.0 of or Document Editor application improvised with composite pattern.

  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
#include <iostream>
#include <string>
#include <memory>
#include <vector>

using namespace std;

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;    
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_;
        current_state = doc_states::opened;
        cout << "Document : " << name_ << " is open for reading" << endl;
    }
    
     void open_write()
    {
        cout << "Enter the file name to open for writing" << endl;
        cin >> name_;
        current_state = doc_states::opened;
        cout << "Document : " << name_ << " is open for writing" << 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 : 3.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; 
}

Want to see the composite pattern in action?

Document Editor App, Version : 3.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 : 0
Enter the file name to open for reading
Hello
Document : Hello is open for reading
Enter your choice :
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your choice : 1
Document : Hello 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
Document : hello is open for writing
Enter your choice :
File : 0
Edit : 1
Exit : 2
0
Open : 0
Close : 1
Enter your choice : 1
Document : hello 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

As discussed, above when user selected open, it is not a menu item as in the previous versions 1.0 and 2.0. Open itself is a Menu or rather we can call it a sub-menu and it presented user with menu items – “Open For Read”, “Open For Write”. User could select either of these options and henceforth use the Document Editor Application as usual.

Enjoyed the chapter? Let me know in the comment below. Thanks 🙂

Leave a Reply