Untitled

mail@pastecode.io avatar
unknown
c_cpp
a year ago
1.7 kB
1
Indexable
Never
#include <mutex>

class StateMachine {
public:
    static StateMachine& getInstance() {
        if (instance_ == nullptr) {
            std::lock_guard<std::mutex> lock(mutex_);
            if (instance_ == nullptr) {
                instance_ = new StateMachine();
            }
        }
        return *instance_;
    }

    void transition() {
        std::lock_guard<std::mutex> lock(mutex_);
        switch (state_) {
            case State::Initial:
                state_ = State::Processing;
                break;
            case State::Processing:
                state_ = State::Completed;
                break;
            case State::Completed:
                // Do nothing, stay in the completed state
                break;
        }
        notify();
    }

    State get_state() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return state_;
    }

    void attach(StateObserver* observer) {
        std::lock_guard<std::mutex> lock(mutex_);
        observers_.push_back(observer);
    }

    void detach(StateObserver* observer) {
        std::lock_guard<std::mutex> lock(mutex_);
        auto it = std::find(observers_.begin(), observers_.end(), observer);
        if (it != observers_.end()) {
            observers_.erase(it);
        }
    }

    void notify() const {
        std::lock_guard<std::mutex> lock(mutex_);
        for (auto observer : observers_) {
            observer->onStateChange(state_);
        }
    }

private:
    StateMachine() : state_(State::Initial) {}

    static StateMachine* instance_;
    static std::mutex mutex_;

    State state_;
    std::vector<StateObserver*> observers_;
};

StateMachine* StateMachine::instance_ = nullptr;
std::mutex StateMachine::mutex_;