DEV Community

Cover image for Creational Patterns : Factory Method
Common Khadka
Common Khadka

Posted on

Creational Patterns : Factory Method

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!
}
Enter fullscreen mode Exit fullscreen mode

}

Enter fullscreen mode Exit fullscreen mode




Key Points:

  1. IAnimal: Defines the interface for the objects created.
  2. Concrete Classes (Dog, Cat): Implement the interface.
  3. Abstract Factory (AnimalFactory): Declares the method for creating objects.
  4. 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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay