#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;
};
class UART_stream:public OutputStream{
public:
void write(const char* msg) override {
cout << "UART:" << msg << endl;
}
};
class SPI_stream:public OutputStream{
public:
void write(const char* msg) override{
cout << "SPI:" << msg << endl;
}
};
/*
TASK FOR LEARNER:
- Implement two concrete OutputStream classes:
- UART stream
- SPI stream
- Implement the factory function below to:
- Select the correct stream at runtime
- Return nullptr for invalid transport values
DO NOT:
- Modify main()
- Add transport logic to logging code
*/
// Factory function (to be implemented)
OutputStream* selectStream(int type);
OutputStream* selectStream(int type) {
if (type == 1) {
return new UART_stream(); // Runtime selection [cite: 21]
} else if (type == 2) {
return new SPI_stream(); // Runtime selection [cite: 21]
}
return nullptr; // Trả về nullptr nếu giá trị không hợp lệ
}
// Transport-independent logging logic
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;
}
Input
1 2 Hello World
Expected Output
UART:Hello UART:World