Runtime Logging Abstraction

#include <iostream>
using namespace std;

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

class UART_stream : public OutputStream{
public:
    void write (const char* msg) override {
        cout << "UART:" << msg << endl;
    }
    ~UART_stream(){}
};

class SPI_stream : public OutputStream{
public:
    void write (const char* msg) override {
        cout << "SPI:" << msg <<endl;
    }
    ~SPI_stream(){}
};

// Factory function (to be implemented)
OutputStream* selectStream(int type){
    if (type == 1) {
        static UART_stream uartstream;
        return &uartstream;
    }
    else if (type == 2) {
        static SPI_stream spistream;
        return &spistream;
    }
    else {
        return nullptr;
    } 
};

// Transport-independent logging logic
void logMessage(OutputStream* stream, const char* msg) {
    if(stream) {
        stream->write(msg);
    }
    else {
        cout << "" << endl;
    }
}

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;
}
Upvote
Downvote
Loading...

Input

1 2 Hello World

Expected Output

UART:Hello UART:World