Contents
When would you use a factory constructor?
Use a factory only when you need extra control with object creation, in a way that couldn’t be done with constructors. Factories have the possibility of caching for example. Another way to use factories is in a scenario where you do not know the type you want to construct.
Can a factory method be static?
A static factory method is a public static method on the object that returns a new instance of the object. These type of methods share the same benefits as the traditional factory method design pattern. This is especially useful for value objects that don’t have a separate interface and implementation class.
Which is better, a static factory method or a constructor?
Static factory methods can have meaningful names, hence explicitly conveying what they do. Static factory methods can return the same type that implements the method(s), a subtype, and also primitives, so they offer a more flexible range of returning types.
Which is better constructor or factory method in OOP?
For everything else a better approach is to use static factory method or in more complex cases a separate factory or builder class. Do minimal work in the constructor. Constructors should not do much work other than to capture the constructor parameters.
When to use factory method in abstract class?
The factory method is often used to hide the exact type of the object being created. An abstract class can have a static factory method, which then selects the concrete derived class to instantiate depending on some condition. Only the abstract base class is publicly documented.
When do factory methods help in C #?
Another common case where factory methods help (in languages like C# which don’t support type inference from constructor) is when you have to minimize type parameter specification. Consider the common case of Tuple class. You can either do: