C++: the observer pattern with std::function

The observer pattern separates the code that produces an event from the code that reacts to it. The publisher keeps a list of callbacks and calls each one when something happens. New behavior, such as logging or an email, is added by subscribing another callback, with no change to the publisher.

C++
#include <functional>
#include <iostream>
#include <string>
#include <vector>

class EventBus {
 public:
  void subscribe(std::function<void(const std::string&)> listener) {
    listeners_.push_back(std::move(listener));
  }

  void publish(const std::string& event) const {
    for (const auto& listener : listeners_) {
      listener(event);
    }
  }

 private:
  std::vector<std::function<void(const std::string&)>> listeners_;
};

int main() {
  EventBus bus;
  std::vector<std::string> log;

  bus.subscribe([&log](const std::string& e) { log.push_back(e); });
  bus.subscribe([](const std::string& e) { std::cout << "got " << e << "\n"; });

  bus.publish("order_placed");
  bus.publish("order_shipped");
  std::cout << "logged " << log.size() << " events\n";
}
Read the full lesson