yy1717
2023-03-31 4bd08f0355b6b2cf3c027202d5ad301b4e182953
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// 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