Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now

Factory Method Design Pattern in C#


in this article, we will discuss the Factory Method Design Pattern in C# with examples. It is a Creational Design Pattern. Previously we discussed the Factory Design Pattern which is also a part of the Creation design pattern.

What is the Factory Method Design Pattern?

As per Factory Method Design Pattern is used when we want to create the object of the class without exposing the logic of object creation to the client. 

According to the Gang of Four Definition “Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method class defer instantiation it uses to subclasses”.

to implement it in the factory method design pattern we need to create the abstract class as part of the Factory class which will create an object and return the object of the product class, and here subclasses will decide which class needs to instantiate. 

The Factory Method Design Pattern is a creational pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. This pattern helps in defining a method that will create objects, and it lets the subclasses decide which class to instantiate.

Here is a real-time example in C#: creating a logging framework where different types of loggers (e.g., Console Logger, File Logger) can be instantiated based on the configuration.

Step 1: Define the Product Interface

public interface ILogger
{
    void Log(string message);
}

Step 2: Implement Concrete Products
public class ConsoleLogger : ILogger
{
    public void Log(string message)
    {
        Console.WriteLine($"Console Logger: {message}");
    }
}

public class FileLogger : ILogger
{
    public void Log(string message)
    {
        // For demonstration purposes, we'll just simulate logging to a file
        Console.WriteLine($"File Logger: {message}");
    }
}


Step 3: Define the Creator Class
public abstract class LoggerFactory
{
    public abstract ILogger CreateLogger();

    public void LogMessage(string message)
    {
        var logger = CreateLogger();
        logger.Log(message);
    }
}


Step 4: Implement Concrete Creators
public class ConsoleLoggerFactory : LoggerFactory
{
    public override ILogger CreateLogger()
    {
        return new ConsoleLogger();
    }
}

public class FileLoggerFactory : LoggerFactory
{
    public override ILogger CreateLogger()
    {
        return new FileLogger();
    }
}

Step 5: Use the Factory Method Pattern

class Program
{
    static void Main(string[] args)
    {
        LoggerFactory loggerFactory;

        // Using Console Logger
        loggerFactory = new ConsoleLoggerFactory();
        loggerFactory.LogMessage("This is a message for the console logger.");

        // Using File Logger
        loggerFactory = new FileLoggerFactory();
        loggerFactory.LogMessage("This is a message for the file logger.");
    }
}

Explanation

  1. ILogger: The product interface that defines the Log method.
  2. ConsoleLogger and FileLogger: Concrete product classes that implement the ILogger interface.
  3. LoggerFactory: The abstract creator class that defines the factory method CreateLogger. It also provides a LogMessage method that uses the logger created by the factory method.
  4. ConsoleLoggerFactory and FileLoggerFactory: Concrete creator classes that implement the factory method to create instances of ConsoleLogger and FileLogger, respectively.
  5. Program: The client code that uses the factory method pattern to log messages using different types of loggers.

Summary

The Factory Method Design Pattern:

  • Defines an interface for creating an object, but lets subclasses alter the type of object that will be created.
  • Helps in decoupling the client code from the concrete classes it needs to instantiate.
  • Provides flexibility to introduce new types of loggers without modifying the client code.

In this example, the logging framework can be extended to support more types of loggers (e.g., Database Logger, Network Logger) by simply adding new concrete creator classes without changing the existing client code.

 

 

Share this

Related Posts

Previous
Next Post »

1 comments:

Write comments
Anonymous
February 6, 2022 at 12:59 AM delete


Nice and simple way to understand the Factory method design pattern . Thanks

Reply
avatar

Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now