/// 1.定义数据访问接口
class IDataAccessInterface
{
public:
virtual IDataInterface(){}
/// 执行数据库 增删改操作
virtual void exeSql(string strSql) = 0;
};
/// 2.数据访问接口实现类
class CDataAccessImp: public IDataInterface
{
CDataAccessImp(){}
virtual ~CDataAccessImp() {}
void exeSql(string strSql) {cout<<"CDataAccessImp"<<endl;}
};
/// 3.获取数据库实例的工厂
/// 不需要在工厂的getInstance中进行大量的if判断(类似java的反射)
template<typename T>
class CFactoryManager
{
public:
static SmartPtr<IDataInterface> getInstance();
};
template<class T>
SmartPtr<IDataInterface> CFactoryManager<T>::getInstance()
{
SmartPtr<IDataInterface> pImp(new T());
return pImp;
}
/// 4.测试如下:
SmartPtr<IDataAccessInterface> pDataAccessInterface = CFactoryManager<CDataAccessImp>::getInstance();
pDataAccessInterface->exeSql("DELETE FROM student WHERE ID=1");
C++模板工厂示例
原文:https://www.cnblogs.com/kinglxg/p/13166360.html