DEV Community

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

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?