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
- 2020 Best Tech Startups in Leawood - June 2, 2020
- From Funeral Director to Customer Success Director How Megan Amos Found Her Dream Career in Tech - May 28, 2020
- What is Code Profiling? Learn the 3 Types of Code Profilers - May 20, 2020
- What Is SDLC? Understand the Software Development Life Cycle - April 8, 2020
- Profile of a Founder: Matt Watson of Stackify - April 2, 2020