The Observer Pattern is commonly used in financial systems to ensure that the components of the system respond dynamically to changes in market data, portfolio values, or other financial indicators. This design pattern allows an object (the subject) to maintain a list of its dependents (observers) and notify them automatically of any state changes, facilitating a publish-subscribe mechanism.
// Observer interface
class Observer {
public:
virtual void update(float stockPrice) = 0;
};
// Subject interface
class Subject {
public:
virtual void attach(Observer* observer) = 0;
virtual void detach(Observer* observer) = 0;
virtual void notify() = 0;
};
// Concrete Subject
class Stock : public Subject {
private:
std::vector observers;
float stockPrice;
public:
void attach(Observer* observer) override {
observers.push_back(observer);
}
void detach(Observer* observer) override {
observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
}
void notify() override {
for (Observer* observer : observers) {
observer->update(stockPrice);
}
}
void setPrice(float price) {
stockPrice = price;
notify(); // Notify observers about the price change
}
};
// Concrete Observer
class Investor : public Observer {
private:
std::string name;
public:
Investor(const std::string& name) : name(name) {}
void update(float stockPrice) override {
std::cout << "Investor " << name << " notified. New stock price: " << stockPrice << std::endl;
}
};
// Usage
int main() {
Stock stock;
Investor investor1("Alice");
Investor investor2("Bob");
stock.attach(&investor1);
stock.attach(&investor2);
stock.setPrice(150.0f); // Notify investors of new price
stock.setPrice(155.0f); // Notify investors of new price
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?