DP: Decorator

Decorator dynamically adds new behavior to an object without modifying its structure. It wraps the original object and enhances functionality.

Used in logging layers, encryption layers, sensor filtering, and communication stacks.

  • Adds behavior at runtime
  • Avoids subclass explosion

C Example

c
#include <stdio.h>

void sendData(const char* msg) {
    printf("Sending: %s\n", msg);
}

void encryptedSend(const char* msg) {
    printf("Encrypting...\n");
    sendData(msg);
}

int main() {
    encryptedSend("Hello");
}

C++ Example

cpp
#include <iostream>
using namespace std;

class Notifier {
public:
    virtual void send(string msg) {
        cout << "Send: " << msg << endl;
    }
};

class EncryptDecorator : public Notifier {
    Notifier* wrappee;
public:
    EncryptDecorator(Notifier* n) : wrappee(n) {}
    void send(string msg) override {
        cout << "Encrypting...\n";
        wrappee->send(msg);
    }
};

int main() {
    Notifier base;
    EncryptDecorator enc(&base);
    enc.send("Hello");
}