Used in UI hierarchies, file systems, device groups, and IoT device grouping.
- Hierarchical structures
- Treat single & group uniformly
C Example
#include <stdio.h>
void lightOn() { printf("Light ON\n"); }
void fanOn() { printf("Fan ON\n"); }
void roomOn() {
lightOn();
fanOn();
}
int main() {
roomOn();
}
C++ Example
#include <iostream>
#include <vector>
using namespace std;
class Device {
public:
virtual void on() = 0;
};
class Light : public Device {
public:
void on() override { cout << "Light ON\n"; }
};
class Group : public Device {
vector<Device*> devices;
public:
void add(Device* d){ devices.push_back(d); }
void on() override {
for(auto d: devices) d->on();
}
};
int main() {
Light l1, l2;
Group room;
room.add(&l1);
room.add(&l2);
room.on();
}