125. Board-Independent Status Indicator

#include <iostream>
using namespace std;

/*
Select exactly ONE hardware board at build time.
*/
// #define BOARD_TYPE_A
#define BOARD_TYPE_B

class StatusIndicator {
public:
    virtual void toggle() = 0;
    virtual bool isOn() const = 0;
    virtual ~StatusIndicator() = default;
};

#if defined(BOARD_TYPE_A) && defined(BOARD_TYPE_B)
#error "Select only one hardware board"
#endif

#if !defined(BOARD_TYPE_A) && !defined(BOARD_TYPE_B)
#error "No hardware board selected"
#endif

#ifdef BOARD_TYPE_A

class BoardAIndicator : public StatusIndicator {
    bool state = false;
public:
    void toggle() override { state = !state; }
    bool isOn() const override { return state; }
};

StatusIndicator& getStatusIndicator() {
    static BoardAIndicator instance;
    return instance;
}

#elif defined(BOARD_TYPE_B)

class BoardBIndicator : public StatusIndicator {
    bool state = false;
public:
    void toggle() override { state = !state; }
    bool isOn() const override { return state; }
};

StatusIndicator& getStatusIndicator() {
    static BoardBIndicator instance;
    return instance;
}

#endif

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

    StatusIndicator& indicator = getStatusIndicator();

    for (int i = 0; i < n; ++i) {
        int evt;
        cin >> evt;

        if (evt == 1) {
            indicator.toggle();
        }

        cout << (indicator.isOn() ? "STATUS=ON\n" : "STATUS=OFF\n");
    }

    return 0;
}

Explanation & Logic Summary:

  • The template code exposes only an abstract interface and a factory declaration, making the program incomplete.
  • The solution introduces two board-specific implementations hidden behind a common abstraction.
  • Conditional compilation enforces build-time hardware selection and prevents invalid configurations.
  • The factory function provides the correct implementation without modifying application logic.
  • This ensures hardware independence through enforced abstraction.

Firmware Relevance & Real-World Context:

  • Embedded firmware must remain stable while hardware boards change across product variants.
  • Build-time hardware selection avoids unsafe runtime decisions and reduces binary size.
  • Abstracting board-specific behavior behind a stable interface is a core industry practice.
  • This problem mirrors how professional firmware isolates hardware differences while preserving application logic.

 

 

 

Loading...

Input

5 1 1 0 1 1

Expected Output

STATUS=ON STATUS=OFF STATUS=OFF STATUS=ON STATUS=OFF