C++语言: 高亮代码由发芽网提供
template <class R, class P1, class P2>
class IDelegate
{
public:
virtual R Invoke(P1, P2) = 0;
};
template <class T, class R, class P1, class P2>
class CDelegate : public IDelegate<R, P1, P2>
{
protected:
typedef R (T::*pfnHandle)(P1, P2);
const pfnHandle m_pfn;
T* const m_pThis;
public:
CDelegate(T* const pThis, const pfnHandle pfn)
:m_pThis(pThis), m_pfn(pfn)
{
if (m_pThis == NULL || m_pfn == NULL)
{
throw;
}
}
virtual R Invoke(P1 p1, P2 p2)
{
return (m_pThis->*m_pfn)(p1, p2);
}
};
class CDelegateSource
{
public:
CDelegateSource()
: m_lpCallBack(NULL)
{
}
void SetCallBack(IDelegate<bool, int, int>* newVal)
{
m_lpCallBack = newVal;
}
void DoSomething()
{
for (int i = 0; i < 10; i++)
{
if (m_lpCallBack != NULL)
{
m_lpCallBack->Invoke(i, i * i);
}
}
}
private:
IDelegate<bool, int, int>* m_lpCallBack;
};
class CDelegateTester
{
private:
bool OnCallBack(int nParam1, int nParam2)
{
printf("OnCallBack -> nParam1:%d, nParam2:%d ", nParam1, nParam2);
return true;
}
CDelegate<CDelegateTester, bool, int, int> m_OnCallBack;
public:
CDelegateTester()
: m_OnCallBack(this, OnCallBack)
{
}
void Execute()
{
CDelegateSource src;
src.SetCallBack(&m_OnCallBack);
src.DoSomething();
}
};
void main()
{
CDelegateTester Tester;
Tester.Execute();
getchar();
}
class IDelegate
{
public:
virtual R Invoke(P1, P2) = 0;
};
template <class T, class R, class P1, class P2>
class CDelegate : public IDelegate<R, P1, P2>
{
protected:
typedef R (T::*pfnHandle)(P1, P2);
const pfnHandle m_pfn;
T* const m_pThis;
public:
CDelegate(T* const pThis, const pfnHandle pfn)
:m_pThis(pThis), m_pfn(pfn)
{
if (m_pThis == NULL || m_pfn == NULL)
{
throw;
}
}
virtual R Invoke(P1 p1, P2 p2)
{
return (m_pThis->*m_pfn)(p1, p2);
}
};
class CDelegateSource
{
public:
CDelegateSource()
: m_lpCallBack(NULL)
{
}
void SetCallBack(IDelegate<bool, int, int>* newVal)
{
m_lpCallBack = newVal;
}
void DoSomething()
{
for (int i = 0; i < 10; i++)
{
if (m_lpCallBack != NULL)
{
m_lpCallBack->Invoke(i, i * i);
}
}
}
private:
IDelegate<bool, int, int>* m_lpCallBack;
};
class CDelegateTester
{
private:
bool OnCallBack(int nParam1, int nParam2)
{
printf("OnCallBack -> nParam1:%d, nParam2:%d ", nParam1, nParam2);
return true;
}
CDelegate<CDelegateTester, bool, int, int> m_OnCallBack;
public:
CDelegateTester()
: m_OnCallBack(this, OnCallBack)
{
}
void Execute()
{
CDelegateSource src;
src.SetCallBack(&m_OnCallBack);
src.DoSomething();
}
};
void main()
{
CDelegateTester Tester;
Tester.Execute();
getchar();
}
相关热门文章
给主人留下些什么吧!~~
评论热议