I have been trying to get a working factory pattern up and running, eventually for a simple strategy game. I think I now have the creation part working.
I can create new objects and store then in a vector (is this the "correct" way to store them?). However, I don't see how to access an object once it is stored. If I had an object with a function that say, made its attached sprite rotate, how would I call this function? How would I know which object is which?
class Sprite
{
public:
virtualvoid TurnLeft(void) = 0;
virtualvoid TurnRight(void) = 0;
virtualvoid Move(int direction, int steps) = 0;
}
class Human : public Sprite
{
//At this point you need to give TurnLeft(), TurnRight(), and Move() a definition.
void TurnLeft(void)
{
//Assuming a console:
cout << "I am a human turning left.";
}
//Do something similar with the other abstract functions.
...
}
...
//Your vector would be of type Sprite:
std::vector<Sprite> g_spritesCol;
By using the above technique (base class-derived classes), you don't need to know the specific implementation of each sprite. You just obtain the element with an iterator or something else and call for the appropriate function. A human will turn the way humans turn, while other characters will turn the way they are supposed to turn, etc.
I'm no STL expert, but I believe you can access an individual item as you would with a regular array. Furthermore, you can use iterators to traverse the vector:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
std::vector<Sprite*> g_spritesCol;
...
void MakeThemAllMove(void)
{
for (vector<Sprite*>::iterator it = g_spritesCol.begin(); it != g_spritesCol.end(); it++)
{
(*it)->TurnLeft();
}
}
...
//Or accessing a specific one by index:
g_spritesCol[3]->TurnLeft();
If there is some kind of identifier to look up specific elements, you could store them in an associative container rather than a vector. This would make look ups of a specific one more efficient--logarithmic rather than linear.