Hey bit stuck trying to make a Factory which creates multiple objects

e.g.

I want 10 rabbits, 6 foxes, 4 dogs + more animals

instead of three for loops like this one

for(int i = 0; i < foxCount; i++)
{
Fox fox = new Fox();
}

Is there a way using a Factory to do this in one loop? somehow use a string for creating these objects?

Was thinking of something like this

for(int i = 0; i<20; i++)
{
if(i<10 && i>0)Rabbit r = new Rabbit();
if(i<16 && i>10)Fox f = new Fox();
if(i<20 && i>16)Dog r = new Dog();

}

is that the best way or is there a more elegant solution? also Am I actually using the factory pattern correctly by doing this?

Sure it is:

Rabit[] rabits = new Rabit[10];
Fox[] foxes = new Fox[6];
Dog[] dogs = new Dog[4];
for(int i = 0; i < 10;i++)
{
   Rabit r = new Rabit();
   rabits[i] = r;
   if(i < 6)
   {
       Fox f = new Fox();
       foxes[i] = f;
   }
   if(i < 4)
   {
       Dog d = new Dog();
       dogs[i] = d;
   }
}

Now you have 3 arrays of the classes

If you dont want to have classes in the array, simply dont use array, and create classes as abouve:

for(int i = 0; i < 10;i++)
{
   Rabit r = new Rabit();
   if(i < 6)
       Fox f = new Fox();
   if(i < 4)
       Dog d = new Dog();
}
commented: Thx that works great! +1

That does the trick, thx!

:) np
I am glad it does.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.