Factory Method design pattern and how it can be used in an ASP.NET Core application
The Factory Method design pattern is a creational pattern that provides an interface for creating objects but delegates the actual object creation to subclasses. It allows for creating objects without specifying the exact class of the object that will be created. In an ASP.NET Core application, the Factory Method pattern can be used to encapsulate the object creation process and provide a flexible way to create instances of different classes based on specific conditions or configurations.
Example:
1. Define an abstract class or interface, let’s call it ILogger
, which represents the common operations that all logger classes should implement.
public interface ILogger
{
void Log(string message);
}
2. Create concrete logger classes that implement the ILogger
interface. For example, you can have FileLogger
, DatabaseLogger
, and EmailLogger
classes.
public class FileLogger : ILogger
{
public void Log(string message)
{
// Logic to log message to a file
}
}
public class DatabaseLogger : ILogger
{
public void Log(string message)
{
// Logic to log message to a database
}
}
public class EmailLogger : ILogger
{
public void Log(string message)
{
// Logic to send an email with the log message
}
}
3. Create a factory class, let’s call it LoggerFactory
, that contains a factory method responsible for creating instances of different logger classes based on a provided parameter or condition.
public class LoggerFactory
{
public ILogger CreateLogger(LoggerType type)
{
switch (type)
{
case LoggerType.File:
return new FileLogger();
case LoggerType.Database:
return new DatabaseLogger();
case LoggerType.Email:
return new EmailLogger();
default:
throw new ArgumentException("Invalid logger type.");
}
}
}
public enum LoggerType
{
File,
Database,
Email
}
4. In your ASP.NET Core application, you can use the LoggerFactory
to create instances of different logger classes based on a configuration or other conditions.
public class MyService
{
private readonly ILogger _logger;
public MyService(LoggerFactory loggerFactory)
{
// Get the logger based on a configuration or condition
_logger = loggerFactory.CreateLogger(LoggerType.File);
}
public void DoSomething()
{
_logger.Log("Doing something...");
}
}
In this example, the LoggerFactory
encapsulates the object creation process and provides a centralized place to create instances of different logger classes. The MyService
class uses the factory to create the appropriate logger based on the configuration or condition and utilizes the created logger to perform logging.
The Factory Method pattern promotes loose coupling between the client code and the specific logger implementations, allowing for easy extensibility and flexibility in adding new logger types in the future.