The Observer Pattern is a software design pattern in which an object, known as the subject, maintains a list of its dependents, known as observers, and notifies them of state changes, usually by calling one of their methods. This pattern is particularly useful in web servers where certain events need to be broadcast to multiple listeners.
In a web server context, you could use the Observer Pattern to listen for events such as new user registrations, document changes, or system notifications. The following is a simple example of how to implement the Observer Pattern in C++ for a web server application.
#include
#include
#include
// Observer Interface
class Observer {
public:
virtual void update(const std::string &message) = 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 notifyObservers(const std::string &message) {
for (Observer* observer : observers) {
observer->update(message);
}
}
};
// Concrete Observer
class ConcreteObserver : public Observer {
private:
std::string name;
public:
ConcreteObserver(const std::string &name) : name(name) {}
void update(const std::string &message) override {
std::cout << name << " received: " << message << std::endl;
}
};
// Example Usage
int main() {
Subject subject;
ConcreteObserver observer1("Observer 1");
ConcreteObserver observer2("Observer 2");
subject.addObserver(&observer1);
subject.addObserver(&observer2);
subject.notifyObservers("New user registered!");
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?