Factory — create objects without specifying class.
Basic factory:
1public interface IAnimal2{3 string Speak();4}56public class Dog : IAnimal { public string Speak() => "Woof"; }7public class Cat : IAnimal { public string Speak() => "Meow"; }89public static class AnimalFactory10{11 public static IAnimal Create(string type) => type switch12 {13 "dog" => new Dog(),14 "cat" => new Cat(),15 _ => throw new ArgumentException()16 };17}
With DI:
1builder.Services.AddScoped<IAnimalFactory, AnimalFactory>();
Key: Factory for object creation abstraction.