Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object initialization and object factories in C++

I'm quite new to c++ development and design and so I apologize in advance in my question is vague or poorly structured. I have several distinct and unrelated hierarchies in my code and I would like to use a generic factory as described and implemented by Alexandrescu to instantiate objects from these hierarchies .
The part I am having difficulty with is the initialization phase. The classes have very different initialization needs. Sometimes the data needed for initialization can be looked up from storage (DB) and in those cases I can encapsulate the initialization procedure in some Init() method of the specific class. But other times the data is known only locally an the moment of instantiation and needs to be passed to the object manually. I'm struggling to come up with a uniform way to do this. Does anyone have any inputs on approaching problems of this kind? Thanks

like image 561
stas Avatar asked Oct 10 '22 04:10

stas


1 Answers

You are hurtling down the Over-Engineering highway... head first.

Factories are seldom required, and no two Factories are alike (as you noticed).

It is useless to try and provide a base class for all your Factories, because this base class will have no clear semantic. What does it build ? Birds ? Cars ? They are unrelated... Objects ? This is not Java!

If you wish to use Factories (for some reason), then a Factory should produce 1 kind of objects, all deriving from a common base class. If you have several kinds of objects, then you will need several kinds of Factories.

And if you find the Factory code repetitive, use a template to hoist the common code.

like image 125
Matthieu M. Avatar answered Oct 12 '22 18:10

Matthieu M.