转自 http://www.cppblog.com/Zezese/archive/2010/07/25/121247.html?opt=admin
1
2
3
4
5 template <class R, class P1, class P2>
6 class IDelegate
7 {
8 public:
9 virtual R Invoke(P1, P2) = 0;
10 };
11
12
13 template <class T, class R, class P1, class P2>
14 class CDelegate : public IDelegate<R, P1, P2>
15 {
16 protected:
17
18 typedef R (T::*pfnHandle)(P1, P2);
19
20 const pfnHandle m_pfn;
21
22 T* const m_pThis;
23
24 public:
25
26 CDelegate(T* const pThis, const pfnHandle pfn)
27 :m_pThis(pThis), m_pfn(pfn)
28 {
29 if (m_pThis == NULL || m_pfn == NULL)
30 {
31 throw;
32 }
33 }
34
35 virtual R Invoke(P1 p1, P2 p2)
36 {
37 return (m_pThis->*m_pfn)(p1, p2);
38 }
39
40 };
41
42 class CDelegateSource
43 {
44 public:
45 CDelegateSource()
46 : m_lpCallBack(NULL)
47 {
48 }
49
50 void SetCallBack(IDelegate<bool, int, int>* newVal)
51 {
52 m_lpCallBack = newVal;
53 }
54
55 void DoSomething()
56 {
57 for (int i = 0; i < 10; i++)
58 {
59 if (m_lpCallBack != NULL)
60 {
61 m_lpCallBack->Invoke(i, i * i);
62 }
63 }
64 }
65
66 private:
67
68 IDelegate<bool, int, int>* m_lpCallBack;
69
70 };
71
72 class CDelegateTester
73 {
74 private:
75
76 bool OnCallBack(int nParam1, int nParam2)
77 {
78 printf("OnCallBack -> nParam1:%d, nParam2:%d\r\n", nParam1, nParam2);
79
80 return true;
81 }
82
83 CDelegate<CDelegateTester, bool, int, int> m_OnCallBack;
84
85 public:
86
87 CDelegateTester()
88 : m_OnCallBack(this, OnCallBack)
89 {
90 }
91
92 void Execute()
93 {
94 CDelegateSource src;
95 src.SetCallBack(&m_OnCallBack);
96 src.DoSomething();
97 }
98 };
99
100 void main()
101 {
102 CDelegateTester Tester;
103 Tester.Execute();
104
105 getchar();
106 }
107
posted on 2010-10-04 09:10
幽幽 阅读(798)
评论(0) 编辑 收藏 引用