So, my Business Code needs some Objects.
It does not know how much objects it needs and it does not know the exact types (because polymorphism is involved).
For me, that sounds for a good reason to go factory pattern.
My code now looks like:
std::vector<AbstractBaseClass*> objectList;
Factory f;
objectList = f.create("path/to/config.txt");
The prototype of the factory's create-method looks like:
std::vector<AbstractBaseClass*> Factory ::create(std::string configFile)
Good news, its working!
The Factory reads the config, and then decides how many objects to create and which concrete types they have.
Well, I did a lot of searching but I couldn't find an example of a factory returning not a single object but a container. Thus, my question: is this good style?
I think yes because this way the whole parsing/creation process is hidden from the business logic. The logic only knows it has some container with a bunch of objects. But maybe you have other opinions?
Please note: this project is all about learning good OOP habits.
Ok, imagine this approach is OK.
I learned, raw pointers are evil. (OK, they are not evil per definition, but I try to avoid them).
So, I want to move to some smart pointers. Lacking boost
and C++11
on this machine I'm starting with auto_ptr
.
OK, new approach:
std::vector< auto_ptr<AbstractBaseClass> > objectList;
Factory f;
objectList = f.create("path/to/config.txt");
And Factory:
std::vector< auto_ptr <AbstractBaseClass> > Factory ::create(std::string configFile)
This looks evil.
And it doesn't compile because at the moment, I'm getting some crazy STL compiler errors.
But, imagin' it compiles.
Is this good?
I've never seen such a construct - a factory returning a container of smart pointers. And because I'm not that expert, I want to ask what you think about this.
On a related note, what smart pointer shall I use?
The business logic is the only owner of the objects, so I guess unique_ptr.
However, I'm not sure if a unique_ptr container can be returned.
shared_ptr is easier to implement, I think.
auto_ptr
is not the right pointer in nearly all cases.unique_ptr
is its replacement.auto_ptr
.