DP: Builder

Builder separates the construction of a complex object from its representation. It is useful when objects require multiple configuration steps.

Used in embedded configuration, packet builders, UI creation, and device setup.

  • Step-by-step construction
  • Improves readability and flexibility

C Example (Factory function)

Using pointer to function

c
#include <stdio.h>

typedef struct {
    int cpu;
    int memory;
} Computer;

void setCPU(Computer* c, int cpu) { c->cpu = cpu; }
void setMemory(Computer* c, int mem) { c->memory = mem; }

int main() {
    Computer pc = {0};

    setCPU(&pc, 4);
    setMemory(&pc, 16);

    printf("CPU: %d, RAM: %d\n", pc.cpu, pc.memory);
}

C++ Example

Using function override

cpp
#include <iostream>
using namespace std;

class Computer {
public:
    int cpu;
    int ram;
};

class ComputerBuilder {
    Computer c;
public:
    ComputerBuilder& setCPU(int cpu) {
        c.cpu = cpu;
        return *this;
    }
    ComputerBuilder& setRAM(int ram) {
        c.ram = ram;
        return *this;
    }
    Computer build() { return c; }
};

int main() {
    Computer pc = ComputerBuilder()
                    .setCPU(8)
                    .setRAM(32)
                    .build();

    cout << pc.cpu << " cores, " << pc.ram << "GB RAM\n";
}