Used in logging layers, encryption layers, sensor filtering, and communication stacks.
- Adds behavior at runtime
- Avoids subclass explosion
C Example
#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
#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");
}