The decorator pattern: From basic to advanced concepts in C++ -- John Farrier

The Decorator Pattern stands out for its unique ability to dynamically add new functionalities to objects without altering their structure.

The decorator pattern: From basic to advanced concepts in C++

John Farrier

From the article:

The Decorator Pattern allows developers to seamlessly decorate or wrap objects with new behaviors or responsibilities, ensuring that the enhancements are scalable, manageable, and, most importantly, interchangeable. This capability is crucial in an era where software requirements are constantly evolving, demanding adaptable and resilient systems to change.

Let’s illustrate this with a basic C++ example. Consider a window in a user interface as the Component. You want to add functionalities like scrollbars or a border without redesigning the window itself.

Here’s a simplified version of how you might implement this:

class Window { // Component
public:
    virtual void draw() = 0;
    virtual ~Window() {}
};

class SimpleWindow : public Window { // Concrete Component
public:
    void draw() override {
        // Draw the window
    }
};

class WindowDecorator : public Window { // Decorator
protected:
    Window* window;
public:
    WindowDecorator(Window* wnd) : window(wnd) {}
    void draw() override {
        window->draw(); // Delegate to the component
    }
};

class ScrollbarWindow : public WindowDecorator { // Concrete Decorator
public:
    ScrollbarWindow(Window* wnd) : WindowDecorator(wnd) {}
    void draw() override {
        WindowDecorator::draw(); // Draw the window
        drawScrollbar(); // Add scrollbar
    }
private:
    void drawScrollbar() {
        // Draw the scrollbar
    }
};


In this example, SimpleWindow is a Concrete Component that can be decorated with additional features. WindowDecorator is a Decorator that holds a reference to a Window object and delegates the draw operation to it. ScrollbarWindow is a Concrete Decorator that adds a scrollbar to the window.

Add a Comment

You must sign in or register to add a comment.

Comments (0)

There are currently no comments on this entry.