The Replace Constructor with Factory Method refactoring allows you to encapsulate a constructor with a static method that returns a new instance of a class.
The Factory Method pattern is a way of creating objects without specifying the exact class of object that will be created. A separate method for creating the objects is generated.
- In the editor, place the caret at a constructor.
- Choose ReSharper | Refactor | Replace Constructor with Factory Method. The
Replace Constructor with Factory Method dialog box opens:
- In the Factory method name text box, specify a name for the new factory method.
- In the In class drop-down list, specify the fully qualified name of the class that the factory method should instantiate.
- Click Next. If no conflicts are found, the refactoring is
applied immediately. Otherwise,
Consider the following example:
After replacing this public constructor with a factory method, the constructor is made private, and a new static factory method is introduced that calls the constructor:
Existing calls to the constructor are replaced with calls to the new factory method.