Inside XML (Inside (New Riders))

     

Recipe 3.15 Converting Constructors to Factory Methods

3.15.1 Problem

You want to convert a constructor to a factory method.

3.15.2 Solution

In Eclipse 3.0, select a constructor declaration or a call to the constructor in the JDT editor, and then select Refactoring Introduce Factory.

This is an Eclipse 3.0-only solution. No equivalent solution exists for versions of Eclipse prior to 3.0.

3.15.3 Discussion

Eclipse 3.0 enables you to convert constructors into factory methods. To do that, you select a constructor declaration or a call to the constructor and then select Refactoring Introduce Factory.

For example, say you had this call to a class's constructor:

public class DisplayApp { private String text; public static void main(String[] args) { DisplayApp DisplayApp = new DisplayApp("Hello"); } public DisplayApp(String text) { super( ); this.text = text; } }

Selecting the constructor call and then selecting Refactoring Introduce Factory opens the Introduce Factory dialog. Here, Eclipse 3.0 will suggest the factory name createDisplayApp . Click OK to accept that name. Eclipse then creates that new factory method, replaces the call to the constructor with a call to that method, and makes the original constructor private:

public class DisplayApp { private String text; public static void main(String[] args) { DisplayApp DisplayApp = createDisplayApp("Hello"); } public static DisplayApp createDisplayApp(java.lang.String text) { return new DisplayApp(text); } /** * @param text */ private DisplayApp(String text) { super( ); this.text = text; } }

Категории