Factory Pattern in C#: What It Is and How It Works
factory pattern in C# is a design pattern that creates objects without exposing the creation logic to the client. It provides a way to delegate the instantiation of objects to a separate method or class, allowing flexible and reusable code.How It Works
The factory pattern works like a factory in real life that produces different products based on demand. Instead of creating objects directly in your code, you ask the factory to make the object for you. This means your code does not need to know the details of how the object is created.
Imagine you want to buy a toy car or a toy plane. Instead of building them yourself, you go to a toy factory that knows how to make both. You just say what you want, and the factory gives you the right toy. This makes your code simpler and easier to change later.
Example
This example shows a simple factory that creates different types of animals based on a given name.
using System; // Product interface interface IAnimal { void Speak(); } // Concrete products class Dog : IAnimal { public void Speak() => Console.WriteLine("Woof!"); } class Cat : IAnimal { public void Speak() => Console.WriteLine("Meow!"); } // Factory class class AnimalFactory { public static IAnimal CreateAnimal(string type) { return type.ToLower() switch { "dog" => new Dog(), "cat" => new Cat(), _ => throw new ArgumentException("Unknown animal type") }; } } class Program { static void Main() { IAnimal animal1 = AnimalFactory.CreateAnimal("dog"); animal1.Speak(); IAnimal animal2 = AnimalFactory.CreateAnimal("cat"); animal2.Speak(); } }
When to Use
Use the factory pattern when you want to separate object creation from usage. It is helpful when your code needs to create objects from a family of related classes but you want to keep your code flexible and easy to extend.
For example, in a game, you might have different types of enemies. Using a factory lets you add new enemy types without changing the main game code. It also helps when the creation process is complex or requires configuration.
Key Points
- The factory pattern hides the details of object creation from the client.
- It promotes loose coupling by separating creation and usage.
- It makes code easier to maintain and extend.
- It is useful when you have multiple related classes to instantiate.