Understanding the Factory Pattern Using .NET and C#

Abdelmajid BACO
3 min readJan 1

Creating Flexible Solutions with the Factory Method Pattern

Photo by carlos aranda on Unsplash

Here is a short article about factory pattern, abstract factory and factory method using C#.

Factory Pattern

The Factory Pattern is an object-oriented design pattern used to create objects without exposing the complexities of their construction. Factory can be implemented in two ways: Factory Method and Abstract Factory.

Factory Method

The Factory Method Pattern can be used as an alternative to constructors in a variety of situations. With this pattern, a factory object is responsible for creating objects from a common interface, thus abstracting the creation process from the user.

Here is an example of how the Factory Method Pattern can be used.

Suppose you need to build a toast notification tool. You could create a ToastCreator class which would be responsible for building the appropriate toast based on the specific notification type. This way, you can create toast notification without needing to know the details of each one.

public abstract class ToastCreator 
{
public abstract Error CreateToastError();
public abstract Warning CreateToastWarning();
public abstract Information CreateToastInformation();
public abstract Success CreateToastSuccess();
}

public class ToastNotification : ToastCreator
{
public override Error CreateToastError()
{
return new Error();
}

public override Warning CreateToastWarning()
{
return new Warning();
}

public override Information CreateToastInformation()
{
return new Information();
}

public override Success CreateToastSuccess()
{
return new Success();
}
}
public class Error
{
public Error() => System.Console.WriteLine("Create toast notification Error");
}
public class Warning
{
public Warning() => System.Console.WriteLine("Create toast notification Warning");
}
public class Information
{
public Information() => System.Console.WriteLine("Create toast notification Information");
}
public class Success
{
public Success() => System.Console.WriteLine("Create toast notification Success");
}
Abdelmajid BACO

Senior Full Stack .Net / Angular Developer, Cloud & Azure DevOps, Carrier Manager, Husband, and Father.

Recommended from Medium

Lists

See more recommendations