126. Runtime Logging Abstraction

#include <iostream>
using namespace std;

class OutputStream {
public:
    virtual void write(const char* msg) = 0;
    virtual ~OutputStream() = default;
};

class UartStream : public OutputStream {
public:
    void write(const char* msg) override {
        cout << "UART:" << msg << "\n";
    }
};

class SpiStream : public OutputStream {
public:
    void write(const char* msg) override {
        cout << "SPI:" << msg << "\n";
    }
};

OutputStream* selectStream(int type) {
    static UartStream uart;
    static SpiStream spi;

    if (type == 1) {
        return &uart;
    }
    if (type == 2) {
        return &spi;
    }
    return nullptr;
}

void logMessage(OutputStream* stream, const char* msg) {
    if (stream) {
        stream->write(msg);
    }
}

int main() {
    int transport;
    cin >> transport;

    int n;
    cin >> n;

    OutputStream* stream = selectStream(transport);

    for (int i = 0; i < n; ++i) {
        char msg[33];
        cin >> msg;
        logMessage(stream, msg);
    }

    return 0;
}

Explanation & Logic Summary:

The program defines an abstract OutputStream interface that represents a generic logging destination.
Concrete implementations (UartStream and SpiStream) encapsulate transport-specific behavior.

A factory function selects the appropriate stream at runtime based on input.
The logging logic interacts only with the abstract interface, ensuring that application code remains independent of the transport mechanism.

Static objects are used to avoid dynamic memory allocation, making the solution suitable for embedded systems.

Firmware Relevance & Real-World Context:

In real firmware, logging destinations may change depending on system mode, boot stage, or connected peripherals.
Hard-coding logging to a specific interface reduces flexibility and reuse.

This pattern demonstrates how runtime abstraction enables a single firmware image to adapt its logging behavior without recompilation, a common requirement in embedded diagnostics, debug consoles, and monitoring subsystems.

 

 

 

 

Loading...

Input

1 2 Hello World

Expected Output

UART:Hello UART:World