Introducing the Factory design pattern

Introducing the Factory design pattern

Read Time : 3 Minutes

Saturday, 18 March 2023

Design patterns are proven solutions to software design problems. They help improve code quality, promote reusability, and increase maintainability. We use them to save time and produce quality, extensible and flexible code. In this article, we are going to introduce the Factory design pattern.

The Factory pattern is a creational pattern that provides an interface to create objects for a super class, but allows derived classes to change the type of objects that are created. This pattern delegates object creation to derived classes.

The factory pattern is useful when a common interface is needed to create objects, but the actual classes created may be different. This pattern separates classes and their constructors well and creates high flexibility in creating objects.

factory design pattern

The factory pattern includes the following components:                                                                              

  • Creator: An abstract base class (Super Class) contains the main method of creating the object. It may also contain code for common functionality for created objects.
  • ConcreteCreator: This is a subclass of Creator that implements the object creation method and returns a new instance of the desired class.
  • Product: An abstract class or an interface for objects is created. The return value of the object creation method is of this type.
  • ConcreteProduct: A class derived from Product that contains its own behavior. In the object creation method, an instance of this class is created.

 

Below is an example of the factory pattern in C# language:

// Product interface
public interface ILogger
{
    void Log(string message);
}
// Concrete product classes
public class FileLogger : ILogger
{
    public void Log(string message)
    {
        // Code to log message to a file
    }
}
public class DatabaseLogger : ILogger
{
    public void Log(string message)
    {
        // Code to log message to a database
    }
}
// Creator abstract class
public abstract class LoggerFactory
{
    public abstract ILogger CreateLogger();
}
// Concrete creator classes
public class FileLoggerFactory : LoggerFactory
{
    public override ILogger CreateLogger()
    {
        return new FileLogger();
    }
}
public class DatabaseLoggerFactory : LoggerFactory
{
    public override ILogger CreateLogger()
    {
        return new DatabaseLogger();
    }
}
// Usage code
class Program
{
    static void Main(string[] args)
    {
        // Use the factory method to create a logger
        LoggerFactory loggerFactory = new FileLoggerFactory();
        ILogger logger = loggerFactory.CreateLogger();
        logger.Log("Log message");
        loggerFactory = new DatabaseLoggerFactory();
        logger = loggerFactory.CreateLogger();
        logger.Log("Log message");
    }
}

In this example, we have an ILogger interface that defines the logging method signature. Then we have two related classes that implement this interface: FileLogger and DatabaseLogger

The LoggerFactory abstract class will be the template for other constructor classes. This class has a method for creating objects that must be implemented by derived classes and returns an ILogger object.

  FileLoggerFactory and DatabaseLoggerFactory classes are classes that inherit from the original LoggerFactory class and implement the CreateLogger method. Each of these constructors creates and returns its own objects.

Then we use all the created classes in the Main function. First, we create a LoggerFactory object and use its CreateLogger method to create an ILogger object. Regardless of which LoggerFactory derivative we use to create the ILogger object, we can use the ILogger object to log to a file or a database.

 

Studying this pattern is not only for the purpose of using it. This pattern has been used in different frameworks, knowing how it works helps us in using these frameworks.

To read about other design patterns, you can use the list below. There is also a code repository on GitHub that includes all the design patterns.

design patterns

Creational:Factory Design Pattern
Builder Design Pattern
Singleton Design Pattern
Prototype Design Pattern
Abstract Factory Design Pattern
Structural:Adapter Design Pattern
Bridge Design Pattern
Composite Design Pattern
Decorator Design Pattern
Facade Design Pattern
Flyweight Design Pattern
Proxy Design Pattern
Behavioral:Chain of Responsibility Design Pattern
Command Design Pattern
Interpreter Design Pattern
Mediator Design Pattern
Memento Design Pattern
Observer Design Pattern
State Design Pattern
Strategy Design Pattern
Template Method Design Pattern
Visitor Design Pattern
Iterator Design Pattern
  • Share:
reza babakhani
Reza Babakhani

I am Reza Babakhani, a software developer. Here I write my experiences, opinions and suggestions about technology. I hope that what I write is useful for you.

Latest post

Service Mesh Simplifying Microservice Communication

In the ever-evolving landscape of software development, microservices architecture has gained considerable popularity due to its scalability, flexibility, and extensibility. However, as the number of microservices in an application increases, it becomes increasingly challenging to manage their communication and ensure that they are all properly visible. This is where Service Mesh comes into play.

The Importance of Edge Computing

Due to the speed of technological evolution, one of the concepts that has attracted a lot of attention and changes the way we interact with digital systems is edge computing.

What is event-driven architecture?

Event-driven architecture (EDA) is a software design pattern that has become increasingly popular in modern software development. In this architecture, the flow of data is determined by the occurrence of events. Unlike traditional centralized systems that are constantly checking for new status. Event-driven architecture is especially useful for systems that need to process large amounts of data in real-time.

leave a comment