带有CComObjects的工厂模式
Factory-pattern with CComObjects
我有一个共享的基类CMyBase,它进一步分为子类CMyFirst和CMySecond。我怎样才能为客户端实现一个工厂接口,这样他们就不需要知道哪一个子对象是用CComObjects创建的?
实际上我要做的是:
CMyBase* CFactory::Create
{
CMyBase* pInst = NULL;
if (something)
{
pInst = new CMyFirst();
}
else
{
pInst = new CMySecond();
}
return pInst;
}
但是我如何创建一个子COM对象的实例?
CComObject<CMyBase>* CFactory::Create
{
HRESULT hr = E_FAIL;
CComObject<CMyBase>* pInst = NULL;
if (something)
{
hr = CComObject<CMyFirst>::CreateInstance(&pInst); // compiler error (see below)
}
else
{
hr = CComObject<CMySecond>::CreateInstance(&pInst); // compiler error (see below)
}
if (SUCCEEDED(hr))
{
pInst->AddRef();
}
return pInst;
}
我明白为什么我得到这个错误,但是我怎么做呢?
error C2664: 'ATL::CComObject<Base>::CreateInstance' : cannot convert parameter 1 from 'ATL::CComObject<Base> *' to 'ATL::CComObject<Base> **'
首先创建派生类,然后在返回之前将其强制转换回基类。
一个例子:
CComObject<CMyBase>* CFactory::Create
{
HRESULT hr = E_FAIL;
CComObject<CMyBase>* pInst = NULL;
if (something)
{
CComObject<CMyFirst>* pFirst = NULL;
hr = CComObject<CMyFirst>::CreateInstance(&pFirst);
pInst = (CComObject<CMyBase>*)pFirst;
}
else
{
CComObject<CMySecond>* pSecond = NULL;
hr = CComObject<CMySecond>::CreateInstance(&pSecond);
pInst = (CComObject<CMyBase>*)pSecond;
}
if (SUCCEEDED(hr))
{
pInst->AddRef();
}
return pInst;
}
相关文章:
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 工厂设计模式优化
- 下面抽象工厂设计模式的实现是正确的吗
- 工厂方法模式使用继承而抽象工厂模式使用组合如何
- 使用宏替换工厂模式样式 API 中的"create()"函数
- 实现通用工厂设计模式
- 使用工厂模式实施单例
- 工厂模式与unique_ptr
- 设计模式的工厂替代方法:具有不同构造函数的类
- 具有多个继承的工厂模式
- 工厂模式和单例模式:未定义的引用
- 在任何编译语言中实现以下语法(用于工厂设计模式)? 最好是 Kotlin,C++
- 共享对象工厂的设计模式
- RAII和工厂设计模式
- 如何使工厂设计模式在C 中
- 对不同的参数使用工厂方法模式
- 实现工厂模式时虚拟功能的多重定义
- dlopen、工厂模式和虚拟方法表
- 工厂模式和std::绑定方法
- 这是哪种设计模式:工厂方法还是抽象工厂