A classic creational design pattern from the gang of four is the factory method pattern. Examples of this pattern typically involve a factory class that constructs objects of a different type. The objects that are created are usually implementations of an interface. This pattern provides a layer between consumption (the caller) and creation (the factory). An additional benefit is that the factory provides named methods to the consumer. This can be especially useful depending on the parameters required to construct the object.
An offshoot of this pattern is to provide static factory methods in the class you want an instance of. 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.
Static factory methods example
To demonstrate the benefits of static factory methods, let’s jump into an example. Which of these time span objects represent 5 seconds?
Not as easy as it sounds unfortunately. This problem is made worse because these constructors take multiple integers. Hours, minutes, seconds, milliseconds. Days? Ticks?
Let’s refactor the example to use the static factory methods that already exist in the TimeSpan class.
It is pretty obvious now which time span objects represent 5 seconds. No code comments or IntelliSense needed.
The key elements to implement this pattern are simple: the factory method must be public, static, and return an instance of the class in which it is defined. If, like TimeSpan, you will have many factory method variants on your class, it’s helpful to name them similarly (“FromX”) but distinctly, to avoid the kind of ambiguity that we see in TimeSpan’s constructor overloads.
Eric Martin Principal Engineer / Stackify
- What is Load Testing? How It Works, Tools, Tutorials, and More - February 5, 2021
- Americaneagle.com and ROC Commerce stay ahead with Retrace - September 25, 2020
- Stackify’s New Pricing: Everything you need to know - September 9, 2020
- INNOVATORS VS COVID 19 Matt Watson, the CEO at Stackify, advises Entrepreneurs to focus on the things that make them happy, regardless if work is a giant dumpster fire - September 2, 2020
- Stackify Joins the 2020 Inc. 5000 List of Fastest-Growing Companies - August 25, 2020