Re: Object Factory and pre-main registering of classes
John <gh14tq5@yahoo.com> kirjutas:
Hi,
I am trying to create an object factory, AFactory, that allows new
object types (of base class A) to be added without changing the
factory.
3. If I compile files separately, link the factory and related classes
into a library and then link the main routine with the library
g++ -c A*.cpp
ar rvs liba.a A*.o
g++ main.cpp -L. -la
the classes do not register themselves before the main function. A
workaround I found was to put the following in AFactory::GetInstance()
function
// FIXME: This forces the maps to register. There should be some
way
// to force the registration without creating this reverse
dependency.
if (m_factory.m_callback.empty())
{
CreateCallBack fnc;
fnc = AType1::CreateA;
// Add all : fnc = ATypeX::CreateA;
}
I don't want to do this because it creates a reverse dependency that
requires modification of the factory to add a new class.
After re-reading your post I realize this is indeed too tight coupling,
meaning that the factory code must know all A* types. What I would do,
would be to add something like this into AFactory code:
// AFactory::GetFactory():
if (!initialized) {
initialized=true; // to avoid infinite recursion
RegisterClassesInLibraryA();
RegisterClassesInLibraryB();
// ...
}
Now in each library (so far you have only one), define the corresponding
registering function like this:
void RegisterClassesInLibraryA() {
AFactory::GetFactory().RegisterA("a1", &AType1::CreateA);
AFactory::GetFactory().RegisterA("a2", &AType2::CreateA);
// ...
}
So the detailed knowledge about your classes is limited to the library
itself. All you have to expose from the library is a single registering
function with a trivial signature.
hth
Paavo