观察者模式

观察者模式:

 1 #ifndef __UIDELEGATE_H__

 2 #define __UIDELEGATE_H__

 3 

 4 #pragma once

 5 

 6 namespace DuiLib {

 7 

 8 class UILIB_API CDelegateBase     

 9 {

10 public:

11     CDelegateBase(void* pObject, void* pFn);

12     CDelegateBase(const CDelegateBase& rhs);

13     virtual ~CDelegateBase();

14     bool Equals(const CDelegateBase& rhs) const;

15     bool operator() (void* param);

16     virtual CDelegateBase* Copy() = 0;

17 

18 protected:

19     void* GetFn();

20     void* GetObject();

21     virtual bool Invoke(void* param) = 0;

22 

23 private:

24     void* m_pObject;

25     void* m_pFn;

26 };

27 

28 class CDelegateStatic: public CDelegateBase

29 {

30     typedef bool (*Fn)(void*);

31 public:

32     CDelegateStatic(Fn pFn) : CDelegateBase(NULL, pFn) { } 

33     CDelegateStatic(const CDelegateStatic& rhs) : CDelegateBase(rhs) { } 

34     virtual CDelegateBase* Copy() { return new CDelegateStatic(*this); }

35 

36 protected:

37     virtual bool Invoke(void* param)

38     {

39         Fn pFn = (Fn)GetFn();

40         return (*pFn)(param); 

41     }

42 };

43 

44 template <class O, class T>

45 class CDelegate : public CDelegateBase

46 {

47     typedef bool (T::* Fn)(void*);

48 public:

49     CDelegate(O* pObj, Fn pFn) : CDelegateBase(pObj, &pFn), m_pFn(pFn) { }

50     CDelegate(const CDelegate& rhs) : CDelegateBase(rhs) { m_pFn = rhs.m_pFn; } 

51     virtual CDelegateBase* Copy() { return new CDelegate(*this); }

52 

53 protected:

54     virtual bool Invoke(void* param)

55     {

56         O* pObject = (O*) GetObject();

57         return (pObject->*m_pFn)(param); 

58     }  

59 

60 private:

61     Fn m_pFn;

62 };

63 

64 template <class O, class T>

65 CDelegate<O, T> MakeDelegate(O* pObject, bool (T::* pFn)(void*))

66 {

67     return CDelegate<O, T>(pObject, pFn);

68 }

69 

70 inline CDelegateStatic MakeDelegate(bool (*pFn)(void*))

71 {

72     return CDelegateStatic(pFn); 

73 }

74 

75 class UILIB_API CEventSource

76 {

77     typedef bool (*FnType)(void*);

78 public:

79     ~CEventSource();

80     operator bool();

81     void operator+= (CDelegateBase& d);

82     void operator+= (FnType pFn);

83     void operator-= (CDelegateBase& d);

84     void operator-= (FnType pFn);

85     bool operator() (void* param);

86 

87 protected:

88     CStdPtrArray m_aDelegates;

89 };

90 

91 } // namespace DuiLib

92 

93 #endif // __UIDELEGATE_H__

你可能感兴趣的:(观察者模式)