178. Lazy Static Singleton

Back To All Submissions
Previous Submission
Next Submission
#include <iostream>
#include <string>

class SystemClock {
private:
    int time_ticks;

    // 1. Private Constructor: Prevents external instantiation
    SystemClock() : time_ticks(0) {}

    // 2. Prevent Copying: Singletons should not be copied or moved
    SystemClock(const SystemClock&) = delete;
    SystemClock& operator=(const SystemClock&) = delete;

public:
    // 3. Static access method
    static SystemClock& getInstance() {
        // 'static' ensures this variable is created once and lives until the program ends.
        // It is initialized lazily (only when getInstance is first called).
        static SystemClock instance; 
        return instance;
    }

    // Increments the internal counter
    void tick() {
        time_ticks++;
    }

    // Returns the current count
    int getTime() const {
        return time_ticks;
    }
};

int main() {
    // Obtain the single reference to our SystemClock
    SystemClock& clk = SystemClock::getInstance();

    int N;
    if (!(std::cin >> N)) return 0;

    for (int i = 0; i < N; ++i) {
        std::string cmd;
        std::cin >> cmd;
        
        if (cmd == "TICK") {
            clk.tick();
        } else if (cmd == "SHOW") {
            std::cout << "Time: " << clk.getTime() << std::endl;
        }
    }
    
    return 0;
}

Solving Approach

 

 

 

 

 

Was this helpful?
Upvote
Downvote