Aggregate Class

class Aggregation::Aggregate

The Aggregate class defines a collection of related components that can be viewed as a unit. More...

Header: #include <aggregation/aggregate.h>
Inherits: QObject

Note: All functions in this class are thread-safe.

Detailed Description

An aggregate is a collection of components that are handled as a unit, such that each component exposes the properties and behavior of the other components in the aggregate to the outside. Specifically that means:

  • They can be cast to each other (using query() and query_all() functions).
  • Their life cycle is coupled. That is, whenever one is deleted, all of them are.

Components can be of any QObject derived type.

You can use an aggregate to simulate multiple inheritance by aggregation. Assuming we have the following code:

 using namespace Aggregation;
 class MyInterface : public QObject { ........ };
 class MyInterfaceEx : public QObject { ........ };
 [...]
 MyInterface *object = new MyInterface; // this is single inheritance

The query function works like a qobject_cast() with normal objects:

 Q_ASSERT(query<MyInterface>(object) == object);
 Q_ASSERT(query<MyInterfaceEx>(object) == 0);

If we want object to also implement the class MyInterfaceEx, but don't want to or cannot use multiple inheritance, we can do it at any point using an aggregate:

 MyInterfaceEx *objectEx = new MyInterfaceEx;
 Aggregate *aggregate = new Aggregate;
 aggregate->add(object);
 aggregate->add(objectEx);

The aggregate bundles the two objects together. If we have any part of the collection we get all parts:

 Q_ASSERT(query<MyInterface>(object) == object);
 Q_ASSERT(query<MyInterfaceEx>(object) == objectEx);
 Q_ASSERT(query<MyInterface>(objectEx) == object);
 Q_ASSERT(query<MyInterfaceEx>(objectEx) == objectEx);

The following deletes all three: object, objectEx and aggregate:

 delete objectEx;
 // or delete object;
 // or delete aggregate;

Aggregation-aware code never uses qobject_cast(). It always uses Aggregation::query(), which behaves like a qobject_cast() as a fallback.