Defining the Class Factory Object

First of all, you need to define an object that implements the IClassFactory interface (or other factory-type interface if applicable). As you would define any other object, you can define a class factory. The following is an example class factory for our TextRender objects in C++:


class CTextRenderFactory : public IClassFactory
   {
   protected:
      ULONG           m_cRef;

   public:
      CTextRenderFactory(void);
      ~CTextRenderFactory(void);

      //IUnknown members
      HRESULT QueryInterface(REFIID, pLPVOID);
      ULONG AddRef(void);
      ULONG Release(void);

      //IClassFactory members
      HRESULT CreateInstance(IUnknown *, REFIID iid, void **ppv
      HRESULT LockServer(BOOL);
   };

Implementing the member functions of this object are fairly straightforward. AddRef and Release do their usual business, with Release calling delete this when the count is decremented to zero. Note that the zero-count event in Release has no effect other than to destroy the object—it does not cause the server to unload as that is the prerogative of LockServer. In any case, the QueryInterface implementation here will return pointers for IUnknown and IClassFactory.