包容和聚合是两种不同的COM对象的代码重用方法.
1.包容:
这种方法是比较容易但也效率比较差的方法.它需要实做它所包容的COM对象的所有
Interface.在包容对象建立时,同时在内部建立被包容的对象,在Client调用它所包容
的对象的方法时,其实是调用的包容对象实现的方法,由包容对象将调用传递给被包容
的对象.
2.聚合:
这种方法是将被包容的对象的Interface publish出来,Client直接调用被包容的对象
的方法. 这种方法有两个问题,第一是Client调用包容对象的IUnknown的queryinterface
方法时,怎样能够得到内部被包容对象的Interface. 第二是被包容对象的AddRef和Release
方法必须影响的是包容对象的参照,而不是被包容对象.
通过以下方法可以达成这个目的:
++++++++以下摘自MSDN++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 When creating the inner object, the outer object must pass its own IUnknown
to the inner object through the pUnkOuter parameter of
IClassFactory::CreateInstance. pUnkOuter in this case is called the controlling
unknown.
2.The inner object must check pUnkOuter in its implementation of CreateInstance.
If this parameter is non-NULL, then
the inner object knows it is being created
as part of an aggregate. If the inner objectdo
es not support aggregation,
then
it must fail with CLASS_E_NOAGGREGATION. If aggregation is supported,
the inner object saves pUnkOuter for later use, butdo
es not call AddRef on it.
The reason is that the inner object's lifetime is entirely contained within
the outer object's lifetime, so there is no need for the call and todo
so
would create a circular reference.
3.If the inner object detects a non-NULL pUnkOuter in CreateInstance, and the
call requests the interface IUnknown itself (as is almost always the case),
the inner object must be sure to return its non-delegating IUnknown.
4.If the inner object itself aggregates other objects (which is unknown to the
outer object) it must pass the same pUnkOuter pointer it receivesdo
wn to the
next inner object.
5.When the outer object is queried for an interface it exposes from the inner
object, the outer object calls QueryInterface in the non-delegating IUnknown
to obtain the pointer to return to the client.
6.The inner object must delegate to the controlling unknown, that is,
pUnkOuter, all IUnknown calls occurring in any interface it implements other
than the non-delegating IUnknown.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
通过以上的说明,我想应该不难理解COM对象聚合.