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
- KC-Based Stackify Is Growing Fast, Hiring Too - December 10, 2019
- Fast-growing Leawood tech company rounds up local investors for $6M raise - December 5, 2019
- More than a podcast host: Matt Watson’s Stackify raises $6M in rapid scaling maneuver - November 25, 2019
- What are Microservices? Code Examples, Best Practices, Tutorials and More - September 13, 2019
- 9 Best Practices to Handle Exceptions in Java - August 22, 2019