DEV Community

Discussion on: How to avoid the Factory pattern in C#

Collapse
 
namhto profile image
Othman Tenich

I don't get why you need this factory anyway. Why not just calling the constructor directly ?

Collapse
 
thfsilvab profile image
Thadeu

Sometimes, objects become too complex to be handled only by the constructor.

Sometimes you'll also want to apply domain rules in the creation of an object.

Collapse
 
shimmer profile image
Brian Berns • Edited

Good point. Because this is a toy example, each factory is only used to create a single animal, so they really serve no purpose. Typically, though, a single factory creates multiple objects - for example, in response to a recurring event, or corresponding to rows in a database, etc.

To keep things simple in our case, imagine if Run looked like this instead:

static void Run(IAnimalFactory factory)
{
    for (var n = 1; n <= 10; ++n)
    {
        var animal = factory.CreateAnimal();
        Console.WriteLine($"Animal #{n} says '{animal.Speak()}'");
    }
}

Since we now create 10 instances of each animal class, some sort of factory makes sense, yes?