17.1.2.  Abstract Factories and Libraries

[ fromfile: factory.xml id: componentfactory ]

We now discuss two libraries, libdataobjects and libcustomer, each with its own ObjectFactory, as shown in the UML diagram in Figure 17.1.

Figure 17.1. Libraries and factories

Libraries and factories

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

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

[ . . . . ]
class CUSTOMER_EXPORT CustomerFactory : public ObjectFactory {
  public:
    static CustomerFactory* instance();

    QObject* newObject(QString classname, QObject* parent=0);
  protected:
    CustomerFactory() {};

};
[ . . . . ]

CustomerFactory inherits the ability to create Address objects from ObjectFactory. In addition, it knows how to create Customer objects. CustomerFactory overrides and extends the newObject(QString) method to support more types, as shown in Example 17.5.

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

[ . . . . ]

QObject* CustomerFactory::newObject (QString className, QObject* parent) {
    qDebug() << QString("CustomerFactory::newObject(%1)")
                       .arg(className);
    QObject* retval =0;                   
    if (className == "Customer")
        retval = new Customer();
    else if (className == "CustomerList") 
        retval = new CustomerList();
    else retval = ObjectFactory::newObject(className, parent);
    if (retval != 0 && retval->parent() == 0) retval->setParent(parent);
    return retval;
}

For each of the three returned objects the parent is set to be the factory. We see this explicitly in the case of a CustomerList object. If the newCustomer() function is called, it also returns an object that is parented by the factory, as we see in Example 17.6.