Skip to content

re: How to avoid the Factory pattern in C# VIEW POST

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

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?

code of conduct - report abuse