Mid From PDF SOLID Design Patterns & SOLID

How do you implement a Factory pattern in C#?

A simple example of Factory Method:

// Product interface

public interface IAnimal
{

void Speak();

}

// Concrete Products

public class Dog : IAnimal
{
public void Speak() => Console.WriteLine("Woof");
}
public class Cat : IAnimal
{
public void Speak() => Console.WriteLine("Meow");
}

// Factory

public class AnimalFactory
{
public static IAnimal CreateAnimal(string animalType)
{
return animalType.ToLower() switch
{

"dog" => new Dog(),

"cat" => new Cat(),

_ => throw new ArgumentException("Invalid animal type")

};

}
}

Usage:

var dog = AnimalFactory.CreateAnimal("dog");

dog.Speak(); // Outputs: Woof

More from Design Patterns in C#

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details