//
|
// Created by YY on 2023/3/30.
|
//
|
|
#ifndef MYAPPLICATION3_OBSERVER_H
|
#define MYAPPLICATION3_OBSERVER_H
|
|
#include <iostream>
|
#include <string>
|
#include <functional>
|
#include <map>
|
|
namespace ilovers {
|
class NonCopyable {
|
protected:
|
NonCopyable() = default;
|
|
~NonCopyable() = default;
|
|
NonCopyable(const NonCopyable &) = delete;
|
|
NonCopyable &operator=(const NonCopyable &) = delete;
|
};
|
|
template<typename Func>
|
class Observer : NonCopyable {
|
public:
|
Observer() {}
|
|
~Observer() {}
|
|
int Connect(Func &&f) {
|
return Assgin(f);
|
}
|
|
int Connect(const Func &f) {
|
return Assgin(f);
|
}
|
|
void Disconnect(int key) {
|
m_connections.erase(key);
|
}
|
|
template<typename... Args>
|
void Notify(Args &&... args) {
|
for (auto &it: m_connections) {
|
it.second(std::forward<Args>(args)...);
|
}
|
}
|
|
private:
|
template<typename F>
|
int Assgin(F &&f) {
|
int k = m_observerId++;
|
m_connections.emplace(k, std::forward<F>(f));
|
return k;
|
}
|
|
int m_observerId = 0;
|
std::map<int, Func> m_connections;
|
};
|
}
|
|
#endif //MYAPPLICATION3_OBSERVER_H
|