Replace Constructor with Factory Method

You want to do more than simple construction when you create an object.

Replace the constructor with a factory method.


	Employee (int type) {

		_type = type;

	}


	static Employee create(int type) {

		return new Employee(type);

	}

For more information see page 304 of Refactoring

Additional Comments

Dimitri Paltchoun pointed out that as well as using Class.forName() and a string for a client to specify the created class, you can also use the class object itself. This would lead you to method like


  static Employee create(Class c){

    try{

      return (Employee)c.newInstance();

    }catch(Exception e){

      throw new IllegalException("Unable to instantiate" +c);

   }

  }

This would be called from this code


   Employee.create(Engineer.class);

| Refactoring Home | | Alphabetical List |