Global objects

O

Oystein Haare

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?

code:

class AbstractFactory { ...};
class AbstractProduct { ...};

class Manager {
public:
static *Manager instance();
registerFactory(AbstractFactory *factory);
};
....

// Header:
class ConcreteProduct : public AbstractProduct { ... };

class ConcreteFactory {
public:
ConcreteFactory()
{
Manager::instance()->registerFactory(this);
}
};

// Cpp:

ConcreteFactory factory; // instanciate a factory object
// (is this a bad idea??)

// implementation
 
S

Siemel Naran

Oystein Haare said:
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;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top