How do I implement the builder pattern in embedded devices with C++?

The Builder Pattern is a design pattern used to create complex objects step by step. It is particularly useful in embedded devices where memory and resources are limited, allowing for an efficient and organized way of constructing objects. This pattern separates the construction of a complex object from its representation, enabling the same construction process to create different representations.

builder pattern, embedded devices, C++, design pattern, object creation, resource management, software architecture, memory efficiency


class Device {
public:
    void setCPU(const std::string &cpu) { this->cpu = cpu; }
    void setRAM(int ram) { this->ram = ram; }
    void setStorage(int storage) { this->storage = storage; }
    void showSpecifications() {
        std::cout << "CPU: " << cpu << "\nRAM: " << ram << " GB\nStorage: " << storage << " GB" << std::endl;
    }
private:
    std::string cpu;
    int ram;
    int storage;
};

class DeviceBuilder {
public:
    DeviceBuilder &setCPU(const std::string &cpu) {
        device.setCPU(cpu);
        return *this;
    }
    DeviceBuilder &setRAM(int ram) {
        device.setRAM(ram);
        return *this;
    }
    DeviceBuilder &setStorage(int storage) {
        device.setStorage(storage);
        return *this;
    }
    Device build() {
        return device;
    }
private:
    Device device;
};

int main() {
    DeviceBuilder builder;
    Device myDevice = builder.setCPU("ARM Cortex-M4")
                              .setRAM(2)
                              .setStorage(32)
                              .build();
    myDevice.showSpecifications();
    return 0;
}
    

builder pattern embedded devices C++ design pattern object creation resource management software architecture memory efficiency