"Oystein Haare" <oy*****@online.no> wrote in message
I'm thinking about sort of a factory-system where the factories get
instanciated on program start (through a global object in the .cpp file),
and registers themselves with a singelton.
Is it a good idea to create global objects like that?
Maybe it won't work at all?
It is a good idea. There are minor variations, like storing pointers to a
function which creates the objects. But the hardest part is to determine if
the creation of the singleton manager must be thread safe, and to make it so
if necessary (as when two objects try to register themselves in the
manager).
class AbstractFactory { ...};
class AbstractProduct { ...};
class Manager {
public:
static *Manager instance();
registerFactory(AbstractFactory *factory);
};
Why not make the input argument to registerFactory an AbstractProduct (or
smart pointer to one)? There seems to be no need for the AbstractFactory
class.
// Manager.h
class Manager {
public:
class RegisterFactory {
explicit RegisterFactory(AbstractProduct *factory);
};
};
Then in each of the cpp files you will just say as follows, as const objects
have internal linkage,
// cpp file 1
#include h file
const Manager::RegisterFactory doregister(new ConcreteProduct1);
....
Personally I like templates so the user doesn't have to enter constructor
arguments
// Manager.h
class Manager {
public:
template <class Product>
class RegisterFactory {
RegisterFactory();
};
private:
template <class Product> friend class RegisterFactory<Product>;
void registerFactory(const AbstractProduct *);
};
// cpp file 1
#include h file
const Manager::template RegisterFactory<ConcreteProduct1> doregister;