Factory Method
The Factory Method is a creational design pattern that defines an interface for creating objects but lets subclasses alter the type of objects that will be created.
It promotes loose coupling and enhances flexibility by delegating object instantiation to subclasses.
This pattern is useful when a class cannot anticipate the type of objects it must create or wants to delegate creation to derived classes.
using System;
// Step 1: Define the Product interface
public interface IAnimal
{
void Speak();
}
// Step 2: Create Concrete Products
public class Dog : IAnimal
{
public void Speak() => Console.WriteLine("Woof!");
}
public class Cat : IAnimal
{
public void Speak() => Console.WriteLine("Meow!");
}
// Step 3: Create the Creator (Factory) Abstract Class
public abstract class AnimalFactory
{
public abstract IAnimal CreateAnimal();
}
// Step 4: Implement Concrete Creators
public class DogFactory : AnimalFactory
{
public override IAnimal CreateAnimal() => new Dog();
}
public class CatFactory : AnimalFactory
{
public override IAnimal CreateAnimal() => new Cat();
}
// Step 5: Client Code
public class Program
{
public static void Main()
{
AnimalFactory dogFactory = new DogFactory();
IAnimal dog = dogFactory.CreateAnimal();
dog.Speak(); // Output: Woof!
AnimalFactory catFactory = new CatFactory();
IAnimal cat = catFactory.CreateAnimal();
cat.Speak(); // Output: Meow!
}
}
Key Points:
IAnimal
: Defines the interface for the objects created.- Concrete Classes (
Dog
,Cat
): Implement the interface.- Abstract Factory (
AnimalFactory
): Declares the method for creating objects.- Concrete Factories (
DogFactory
,CatFactory
): Override the creation method to return specific objects.
This example shows how the Factory Method allows you to encapsulate object creation, making the system scalable and maintaining the open/closed principle.
Top comments (0)