Linux学习之线程封装六:基于模板的面向方面的封装(三个方面)
三个方面:业务逻辑,执行体,协调器(装配前两者)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<pthread.h>
#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include"CLStatus.h"
#include"CLLog.h"
using namespace std;
class CMyFunction
{
public:
CLStatus RunExecutiveFunction(void *pContext)
{
int i = (int)pContext;
cout << i << endl;
return CLStatus(0, 0);
}
};
template<typename TUser, typename TStored>
class CLTypeSaver
{
public:
CLTypeSaver(TUser *pUser)
{
m_pUser = pUser;
}
virtual ~CLTypeSaver()
{
}
static void* CallBackFunc(void *arg)
{
CLTypeSaver<TUser, TStored> *pThis = static_cast<CLTypeSaver<TUser, TStored> *>(arg);
(*(pThis->m_pUser)).template GetStoredType<TStored>();
delete pThis;
return (void *)0;
}
private:
TUser *m_pUser;
};
class CLThread
{
public:
template<typename TDerivedClass>
CLStatus Create()
{
CLTypeSaver<CLThread, TDerivedClass> *pSaver = new CLTypeSaver<CLThread, TDerivedClass>((CLThread *)this);
pthread_t tid;
int r = pthread_create(&tid, NULL, CLTypeSaver<CLThread, TDerivedClass>::CallBackFunc, pSaver);
if(r != 0)
{
CLLog::WriteLogMsg("pthread_create error", r);
return CLStatus(-1, 0);
}
}
template<typename TDerivedClass>
void GetStoredType()
{
TDerivedClass *pDerived = static_cast<TDerivedClass *>(this);
pDerived->ProcessByProxy();
}
};
template<typename TExecutive, typename TExecutiveFunctionProvider>
class CLCoordinator : public TExecutive, public TExecutiveFunctionProvider
{
public:
CLStatus Run(void *pContext)
{
m_pContext = pContext;
TExecutive *pExecutive = static_cast<TExecutive *>(this);
typedef CLCoordinator<TExecutive, TExecutiveFunctionProvider> T;
return (*pExecutive).template Create<T>();
}
void ProcessByProxy()
{
TExecutiveFunctionProvider *pProvider = static_cast<TExecutiveFunctionProvider*>(this);
pProvider->RunExecutiveFunction(m_pContext);
}
private:
void *m_pContext;
};
int main()
{
CLCoordinator<CLThread, CMyFunction> t1;
t1.Run((void *)5);
sleep(5);
return 0;
}
每个模板参数,即基类,代表一个方面
当需要扩展时,即创建不同类型执行体,执行不同业务逻辑时,只需要新增加基类而不是派生类
创建线程还是进程,执行何种业务逻辑,甚至协调器本身均可以装配(执行体可以反过来装配协调器)
关键这一行:
TDerivedClass *pDerived = static_cast<TDerivedClass *>(this);
CLThread如何转换为TDerivedClass呢?
事实上,往下看不难发现在create时我们传递的是CLCoordinator<TExecutive, TExecutiveFunctionProvider>,所以
TStored=TDerivedClass=CLCoordinator<TExecutive, TExecutiveFunctionProvider>,这个static_cast实际上是
CLCoordinator<CLThread, CMyFunction> *pDerived = static_cast<CLCoordinator<CLThread, CMyFunction> *> (CLThread*)
即基类指针转换为派生类指针。
注意两种成员函数调用方式:
1.带模板参数的成员函数,形如:(*pExecutive).template Create<T>(),(*(pThis->m_pUser)).template GetStoredType<TStored>();
2.不带模板参数的成员函数(包括模板类的普通成员函数):pDerived->ProcessByProxy();
TStored保存派生类,
TDerivedClass用于转换后的派生类指针。