16.1.2.  Abstract Factories and Libraries

[ fromfile: factory.xml id: componentfactory ]

Now consider two libraries, libdataobjects and libcustomer, each with its own (concrete) object factory, as shown in the UML diagram in Figure 16.1.

Figure 16.1. Libraries and factories

Libraries and factories

CustomerFactory, defined in Example 16.5, extends the functionality of ObjectFactory.

Example 16.5. src/libs/customer/customerfactory.h

[ . . . . ]
class CUSTOMER_EXPORT CustomerFactory : 
                             public QObject, public ObjectFactory {
  public:
    static CustomerFactory* instance();                      1
    Customer* newCustomer(QString name, QObject* parent=0);  2
    Address* newAddress(QString countryType = "USA", QObject* parent=0);
  private:
    CustomerFactory(QObject* parent=0);
};
[ . . . . ]

1

Singleton factory method.

2

Regular factory method, does not require a typecast.

<include src="src/libs/customer/customerfactory.h" href="src/libs/customer/customerfactory.h" id="custfacth" mode="cpp"/>


CustomerFactory inherits the ability to create Address objects from ObjectFactory. In addition, it knows how to create Customer objects. CustomerFactory needs only to add some QMetaObjects to ObjectFactory::m_knownClasses from the constructor (which is possible because that container is protected). The base-class newObject() method is smart enough to handle the classes added by Customer provided they are properly registered in that container.

Example 16.6. src/libs/customer/customerfactory.cpp

[ . . . . ]


CustomerFactory::CustomerFactory(QObject* parent) : QObject(parent) {
    m_knownClasses["Customer"] = Customer::staticMetaObject;
    m_knownClasses["CustomerList"] = Customer::staticMetaObject;
}

<include src="src/libs/customer/customerfactory.cpp" mode="cpp" href="src/libs/customer/customerfactory.cpp" id="custfact-newobj" segid="ctor"/>