Have you ever found yourself in a situation where you’ve been growing your class, adding more and more constructors all with their own configuration specifics? Have you ever wished that you could take out the object creation code into a separate class and reorganize it to be more readable?
Let’s take a look at a scenario right out of the Refactoring to Patterns book. Here we have several loan constructors all hiding the real intent in the parameters they take:
Now, let’s refactor these constructors into factory methods. To do so, we take each constructor in turn and choose the Replace Constructor With Factory Method in-place refactoring (Ctrl+Shift+R).
Consequently, we can give the new factory method a name, but we can also specify a different class in which to put the factory method.
What you end up with is a factory method in the
Doing this for all relevant constructors will yield a complete factory class. Please note that if you put the factory methods in the originating class (e.g.,
Loan), the corresponding constructors will turn
private. But since we moved these constructors into a separate factory class, the constructors remain