Pattern: AbstractFactory
Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.
Purpose of .NET implementation
You want to create commands for any specific database type in order to obtain data from a database.
This means you can switch between different databases (e.g., SQL Server, MySQL, PostgreSQL) without changing the core logic of your application.
The factory will provide the appropriate concrete implementation of the DBConnection for the database in use..
By using an Abstract Factory, your application can remain agnostic of the specific type of database it is interacting with.
Example in .NET :
AbstractFactory
using Microsoft.Data.SqlClient;
using System.Data.Common;
namespace AbstractFactory;
internal class AbstractFactoryDemo
{
public static void Demo()
{
//create DbConnection factory by using the instance of SqlConnection
DbConnection connection = new SqlConnection();
//create DbCommand instance by using the instance of SqlConnection
DbCommand command = connection.CreateCommand();
//really, the DBCommand is a SqlCommand
SqlCommand? sqlCommand = command as SqlCommand;
//check if the DbCommand is a SqlCommand
Console.WriteLine($"DbCommand is SqlCommand: {sqlCommand != null}");
}
}
See Source Code for Microsoft implementation of AbstractFactory
SourceCode DbConnectionLearn More
WikipediaHomework
Imagine you want to produce loggers.
You have a logger that logs to a file and a logger that logs to a console and a Nothing Logger - a logger that does nothing.
Implement an abstract factory that will allow you to create a logger factory that will create a logger that logs to a file or to a console or nothing.