Skip to content

Structural_patterns

Structural patterns describe how objects are composed to form larger structures.

Convert one interface to another:

class OldAPI {
public:
int process(int data) { return data * 2; }
};
class NewAPI {
public:
virtual int processData(std::string) = 0;
};
class Adapter : public NewAPI {
OldAPI old;
public:
int processData(std::string data) override {
return old.process(std::stoi(data));
}
};

Add behavior dynamically:

class Coffee {
public:
virtual double cost() = 0;
};
class BasicCoffee : public Coffee {
public:
double cost() override { return 5.0; }
};
class MilkDecorator : public Coffee {
Coffee* coffee;
public:
MilkDecorator(Coffee* c) : coffee(c) {}
double cost() override { return coffee->cost() + 1.5; }
};

Simplified interface to complex system:

class CPU { void freeze() {} }
class Memory { void load() {} }
class HardDrive { void read() {} }
class ComputerFacade {
CPU cpu;
Memory memory;
HardDrive hd;
public:
void start() {
cpu.freeze();
memory.load();
hd.read();
}
};

Placeholder for another object:

class RealImage {
public:
void display() { /* Load high-res */ }
};
class ImageProxy {
RealImage* realImage;
public:
void display() {
if (!realImage) {
realImage = new RealImage();
}
realImage->display();
}
};