Observer Manager

Observer is a very popular pattern, however there’s not too many flexible implementations in C++ out there. I decided to write my own bicycle and here’s what came of it.

The codes can be downloaded from https://github.com/fnz/ObserverManager

Here’s a sample use:

class FooBarProtocol : public BaseObserverProtocol {
public:
    virtual void foo() {}
    virtual void bar(const std::string& word) {}
};

The main goal was to support groups rather than single events. In this example FooBarProtocol is a group having two events. In a real world this can be something like InAppProtocol with events called inAppPageOpened, inAppSuccessful and inAppFailed.

Every event group must be publicly inherited from BaseObserverProtocol. This ensures proper unsubscribing upon destruction.

class A : public FooBarProtocol {
public:
	std::string name;
	
	virtual void foo() override {
		std::cout << name << " ";
	}

	virtual void bar(const std::string& word) override {
		std::cout << word << " ";
	}
};

Here A is an observer, listening to both events of FooBarProtocol group. There’s no need to react to all events, so you should override only necessary methods.

void main() {
	A* a = new A();
	a->name = "Mary";
	ObserverManager::subscribe<FooBarProtocol>(a);

	ObserverManager::notify(&FooBarProtocol::foo);
	ObserverManager::notify(&FooBarProtocol::bar, "Poppins");

	ObserverManager::unsubscribe(a);

	delete a;
}

That’s a simple example of how ObserverManager can be used. As long as the vast majority of objects in game development are accessed via pointers, ObserverManager accepts pointers. More examples can be seen in tests.

ObserverManager is thread safe, but before using it from multiple threads make sure your observers are thread safe as well.

That’s all :slight_smile: Critique and suggestions are welcome!

Thanks for sharing and posting this.

Here is more information for anyone on Observer: http://gameprogrammingpatterns.com/observer.html

http://gameprogrammingpatterns.com - these articles are amazing