Recipe 3.15 Converting Constructors to Factory Methods

     

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;     } } 



Eclipse Cookbook
Inside XML (Inside (New Riders))
ISBN: 596007108
EAN: 2147483647
Year: 2006
Pages: 232
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net