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 Abstract Factory design pattern.
The Abstract Factory pattern is a creational design pattern that allows the creation of a collection of related or dependent objects without specifying their class types. In fact, this pattern defines abstract rules for the production of objects and is implemented according to the need in different situations.
The Abstract Factory pattern consists of several key components:
The main advantage of the Abstract Factory pattern is that it provides a way to encapsulate the creation of related objects and does not involve the user in the details of object creation. In addition, in case of changes in the implementation, the user codes will not need to be changed.
In the following, we will understand this pattern better with an example:
// Abstract Product A
public interface IShape
{
void Draw();
}
// Concrete Product A1
public class Circle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a Circle");
}
}
// Concrete Product A2
public class Square : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a Square");
}
}
// Abstract Product B
public interface IColor
{
void Fill();
}
// Concrete Product B1
public class Red : IColor
{
public void Fill()
{
Console.WriteLine("Filling with Red");
}
}
// Concrete Product B2
public class Blue : IColor
{
public void Fill()
{
Console.WriteLine("Filling with Blue");
}
}
// Abstract Factory
public interface IShapeAndColorFactory
{
IShape CreateShape();
IColor CreateColor();
}
// Concrete Factory 1
public class CircleAndRedFactory : IShapeAndColorFactory
{
public IShape CreateShape()
{
return new Circle();
}
public IColor CreateColor()
{
return new Red();
}
}
// Concrete Factory 2
public class SquareAndBlueFactory : IShapeAndColorFactory
{
public IShape CreateShape()
{
return new Square();
}
public IColor CreateColor()
{
return new Blue();
}
}
In this example, we have two Abstract Products named IShape and IColor and their implementation in the form of Circle, Square, Red and Blue. Then we have created an Abstract Factory called IShapeAndColorFactory. Next, we have implemented IshapeAndColorFactory with two modes CircleAndRedFactory and SquareAndBlueFactory.
The IShapeAndColorFactory interface defines methods to create an IShape and an IColor, and the classes that implement it each provide their own methods to create these objects.
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.
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.
leave a comment