重点:
1.利用观察者,注册需要处理的用户(Test)(右值处理方法也是妙处)
2.用户自身采用模板去调用观察者的类(方法甚妙)
- #include
- #include
- #include
- #include
-
- class Test
- {
- public:
- Test() = default;
- ~Test() = default;
-
-
- virtual void DoIt() = 0;
-
-
- };
-
- //每个A和B可以执行自己的判断逻辑
- class TestA: public Test
- {
- public:
- TestA() = default;
- ~TestA() = default;
- template<class T>
- TestA(T* t)
- {
- m_func = [t](const int& num)
- {
- t->GetData(num);
- };
- }
- void DoIt() override
- {
- m_func(10);
- }
- protected:
- std::function<void(const int&)> m_func;
- };
-
- //每个A和B可以执行自己的判断逻辑
- class TestB : public Test
- {
- public:
- TestB() = default;
- ~TestB() = default;
- template<class T>
- TestB(T* t)
- {
- m_func = [t](const int& num, const int& num2)
- {
- t->GetData(num, num2);
- };
- }
- void DoIt() override
- {
- m_func(20,10);
- }
- protected:
- std::function<void(const int&,const int&)> m_func;
- };
-
- class A
- {
- public:
- A() = default;
- ~A() = default;
- //执行不同函数
- void GetData(const int& num)
- {
- std::cout << num * 2 << std::endl;
- }
-
- void GetData(const int& num, const int& t)
- {
- std::cout << num * t << std::endl;
- }
-
- //利用右值引用处理指针
- void AddTest(std::shared_ptr
&& t) - {
- m_test.emplace_back(std::forward
>(t)); - }
-
- void DoIt()
- {
- for (const auto&var: m_test)
- {
- var->DoIt();
- }
- }
-
- public:
- void CreateTest();
-
- private:
- std::vector
> m_test; - };
-
- void A::CreateTest()
- {
- auto testA = std::make_shared
(this); - AddTest(testA);
- auto testB = std::make_shared
(this); - AddTest(testB);
- }
-
- int main() {
- std::shared_ptr a= std::make_shared();
- a->CreateTest();
- a->DoIt();
- return 0;
- }