How do I implement the observer pattern in game engines with C++?

The Observer Pattern is a behavioral design pattern that establishes a one-to-many relationship between objects, allowing one object (the subject) to notify multiple dependent objects (observers) about changes in its state. This pattern is particularly useful in game engines, where different components need to react to changes in the game state.

Implementing the Observer Pattern in C++ for Game Engines

Here's a simple implementation of the Observer pattern in C++ tailored for game engines:

// Observer interface class Observer { public: virtual ~Observer() {} virtual void onNotify(int eventType) = 0; }; // Subject class class Subject { private: std::vector observers; public: void addObserver(Observer* observer) { observers.push_back(observer); } void removeObserver(Observer* observer) { observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end()); } void notify(int eventType) { for (Observer* observer : observers) { observer->onNotify(eventType); } } }; // Example Observer Implementation class Player : public Observer { public: void onNotify(int eventType) override { if (eventType == 1) { std::cout << "Player received an event!" << std::endl; } } }; // Example Subject Implementation class GameEvent : public Subject { public: void triggerEvent() { notify(1); // Notify observers of an event } }; // Usage int main() { GameEvent gameEvent; Player player; gameEvent.addObserver(&player); // Register player as an observer gameEvent.triggerEvent(); // This will notify the player return 0; }

observer pattern design pattern C++ game engine notify observers subject observer