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.
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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?