#include <iostream>
using namespace std;
/*
DESIGN REQUIREMENTS:
- Logging must use a runtime-selected stream abstraction
- Application code must not depend on transport type
- Transport-specific logic must be hidden
*/
// Abstract output stream
class OutputStream {
public:
virtual void write(const char* msg) = 0;
virtual ~OutputStream() = default;
};
// --- TASK IMPLEMENTATION START ---
/**
* UART implementation of the stream.
* Prepends "UART:" to every message.
*/
class UartStream : public OutputStream {
public:
void write(const char* msg) override {
cout << "UART:" << msg << endl;
}
};
/**
* SPI implementation of the stream.
* Prepends "SPI:" to every message.
*/
class SpiStream : public OutputStream {
public:
void write(const char* msg) override {
cout << "SPI:" << msg << endl;
}
};
/**
* Factory function to select the transport at runtime.
* Uses static instances to avoid dynamic memory allocation (no 'new').
*/
OutputStream* selectStream(int type) {
static UartStream uart;
static SpiStream spi;
if (type == 1) {
return &uart;
} else if (type == 2) {
return &spi;
}
return nullptr; // Invalid transport
}
// --- TASK IMPLEMENTATION END ---
// Transport-independent logging logic
void logMessage(OutputStream* stream, const char* msg) {
if (stream) {
stream->write(msg);
}
}
int main() {
int transport;
if (!(cin >> transport)) return 0;
int n;
if (!(cin >> n)) return 0;
OutputStream* stream = selectStream(transport);
for (int i = 0; i < n; ++i) {
char msg[33];
if (cin >> msg) {
logMessage(stream, msg);
}
}
return 0;
}
Input
1 2 Hello World
Expected Output
UART:Hello UART:World