I get the idea of the factory pattern, but I feel that it is really not necessary to use this pattern.
For example, below is some code I saw (C#) that use factory method:
public interface IAnimal
{
void Speak();
}
public class Dog : IAnimal
{
public void Speak()
{
Console.WriteLine("Dog says: Bow-Wow.");
}
}
public class Tiger : IAnimal
{
public void Speak()
{
Console.WriteLine("Tiger says: Halum.");
}
}
public abstract class IAnimalFactory
{
public abstract IAnimal CreateAnimal();
}
public class TigerFactory : IAnimalFactory
{
public override IAnimal CreateAnimal()
{
return new Tiger();
}
}
public class DogFactory : IAnimalFactory
{
public override IAnimal CreateAnimal()
{
return new Dog();
}
}
and client can invoke:
IAnimalFactory tigerFactory = new TigerFactory();
IAnimal aTiger = tigerFactory.MakeAnimal();
aTiger.Speak(); //3 lines of code, plus needing of extra factory classes
but Client can also do like:
IAnimal aTiger = new Tiger();
aTiger.Speak(); //only 2 lines of code
we can see that only 2 lines of code is needed, and we don't need to define factory classes. so why takes extra steps to define and use factories?
Ant P replied that RandomNumberOfAnimalsGenerator needs a factory, but below is my version of the class, still doesn't need any factory.
public class RandomNumberOfAnimalsGenerator
{
private readonly animal ;
public RandomNumberOfAnimalsGenerator(IAnimal animal)
{
this.animal = animal;
}
public List<IAnimal> GetAnimals()
{
var animals = new List<IAnimal>();
var n = RandomNumber();
for(int i=0; i<n; i++)
{
animals.Add(animal);
}
return animals;
}
}
and client invokes:
var RandomNumberOfAnimalsGenerator = new RandomNumberOfAnimalsGenerator(new Tiger());
still doesn't need a factory
RandomNumberOfAnimalsGenerator
doesn't make a random number of animals. It makes exactly 0 new animals, but it adds the same animal to the list several times. Animal factory version: pass it "dog", get [Fido, Spot, Max]. Your version: pass it "Fido", get [Fido, Fido, Fido].IAnimalFactory tigerFactory = new TigerFactory();
And then someday TigerFactory gets switched out for DogFactory, but the variable names will be left as is because scope propagation and too much effort and than new people will be brought into the project and the chaos will be glorious. :3