Composite pattern

Other topics

Remarks:

The composite pattern applies when there is a part-whole hierarchy of objects and a client needs to deal with objects uniformly regardless of the fact that an object might be a leaf (simple object) or a branch (composite object).

pseudocode for a dumb file manager

/* 
* Component is an interface 
* which all elements (files,
* folders, links ...) will implement
*/
class Component
{
public:
    virtual int getSize() const = 0;
};

/*
* File class represents a file
* in file system.   
*/
class File : public Component
{
public:
    virtual int getSize() const {
        // return file size
    }   
};

/*
* Folder is a component and 
* also may contain files and 
* another folders. Folder is a
* composition of components
*/
class Folder : public Component
{
public:
    void addComponent(Component* aComponent) {
        // mList append aComponent;
    }
    void removeComponent(Component* aComponent) {
        // remove aComponent from mList
    }
    virtual int getSize() const {
        int size = 0;
        foreach(component : mList) {
            size += component->getSize();
        }
        return size;
    } 

private:
    list<Component*> mList;
};

Contributors

Topic Id: 9197

Example Ids: 28549

This site is not affiliated with any of the contributors.