Replace Constructor with Factory Method
The Replace Constructor With Factory Method refactoring allows you to hide a constructor and replace it with a static method which returns a new instance of a class.
Example
Before | After |
---|---|
// File Class.java
public class Class {
public Class(String s) {
...
}
}
// File AnotherClass.java
public class AnotherClass {
public void method() {
Class aClass = new Class("string");
}
} | // File Class.java
public class Class {
private Class(String s) {
...
}
public static createClass(String s) {
return new Class(s);
}
}
// File AnotherClass.java
public class AnotherClass {
public void method() {
Class aClass = Class.createClass("string");
}
} |
To replace a constructor with a factory method
- Select the class constructor.
- Open Replace Constructor With Factory Method dialog by choosing on the main menu or on tne context menu of the selection.
- In the Factory method name field, specify the name for the factory method.
- In the In (fully qualified name) field, specify the class, where the method should be created.
- To review the intended changes and make final corrections prior to the refactoring, click Preview. To apply the changes immediately, click Refactor.
Last modified: 29 November 2017