Replace Constructor with Factory Method refactoring
This refactoring helps implement the factory method pattern for an existing class. If you opt to create the factory method in the same class, the refactoring makes the selected constructor private and encapsulates it into a static method that returns a new instance of the class. You can also choose to create the factory method in any other class. In this case, the constructor stays public, you can change its access modifier later, if necessary.
If there are any usages of the constructor, they are replaced with factory method calls.
In the example below, we use the refactoring to add the factory method in the same class:
Before refactoring
class Foo{ public Foo() { // instance initialization }}
After refactoring
class Foo{ public static Foo CreateFoo() { return new Foo(); } private Foo() { // instance initialization }}
In the editor, place the caret at a constructor or choose a constructor in the Structure window window.
Do one of the following:
Press CtrlShift0R and then choose Replace Constructor with Factory Method.
Choose Refactor | Replace Constructor with Factory Method from the main menu.
The Replace Constructor with Factory Method dialog will open.
Specify a name for the factory method or accept the suggested name.
By default, the refactoring creates factory method in the same class. If you want to create the factory method in another class, specify the fully qualified name of the class.
To apply the refactoring, click Next.
If no conflicts are found, JetBrains Rider performs the refactoring immediately. Otherwise, it prompts you to resolve conflicts.
tip
Right after the refactoring has been completed, all changes that it makes anywhere, including other files, are registered as a single operation. So you can use the Undo action Ctrl0Z to roll back all these changes with a single keystroke.
