Member-only story
5 Ways To Implement the Factory Design Pattern in C#
Static, asynchronous, parameterized, inner, and abstract factories
Objects can instantiate other objects directly by calling the new
keyword, but this approach is often not the best choice.
Instantiating the object is a separate responsibility that should be carried over from the client code to separate classes/methods called factories.
Using a Factory design pattern has the following benefits:
- The client code has one less responsibility because it doesn’t need to create objects. This is the responsibility of the factory.
- Factory encapsulates the logic of creating an object that can be reused by many clients.
There are many variations of a Factory pattern, each of which solves a different problem.
1. Static Factory Method
The constructor has the same name as the class in which it is declared. If there are multiple overloaded constructors in the class, they will all have the same name.
Client code that needs to instantiate a class with multiple overloaded constructors may not know which constructor to call without examining the implementation details of the class.
Also, sometimes constructors don’t work at all when they need to have the same number of parameters of the same type.
The following code won’t compile:
public struct TimeSpan
{
public TimeSpan(double seconds)
{
} public TimeSpan(double minutes)
{
}
}
Static factory methods are a good alternative to constructors because they have a unique name that can accurately describe the purpose of the returned instance.
The client code can figure out which factory method to call by reading its name without even looking into the class code.