带有CComObjects的工厂模式

Factory-pattern with CComObjects

本文关键字:模式 工厂 CComObjects 带有      更新时间:2023-10-16

我有一个共享的基类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;
}