Home

 

Using the delegate method generator

The delegate method generator feature allows you to delegate methods from one class to another for better encapsulation. We use a simple example to explain this feature. A car has an engine, and a driver wants to start his car. Figure | -57 shows that the engine is not encapsulated, the PoorDriver has to use the Car and the Engine class to start his car.

Figure 8-57 Simple car example class diagram (before method delegation)

Example | -10 shows how the PoorDriver has to start his car.

Example 8-10 Car, Engine, and PoorDriver classes (compressed)

// Car class
package itso.rad75.example;
import itso.rad75.example.Engine;
public class Car {
	private Engine carEngine = null;
	public Car(Engine carEgine) {
		this.setCarEngine(carEngine);
	}
	public Engine getCarEngine() {
		return carEngine;
	}
	private void setCarEngine(Engine carEngine) {
		if (carEngine != null) {
			this.carEngine = carEngine;
		} else {
			this.carEngine = new Engine();
		}
	}
}

// Engine class
package itso.rad75.example;
public class Engine {
	public void start() {
	// code to start the engine
	}
}

// PoorDriver class
package itso.rad75.example;
import itso.rad75.example.Car;
public class PoorDriver {
	public static void main(String[] args) {
		Car myCar = new Car(null);
		/* How can I start my car?
		 * Do I really have to touch the engine?
		 * - Yes, there is no other way at the moment. 
		 */ 
		myCar.getCarEngine().start();
	}
}

To make the driver happy, we delegate the start method from the Engine class to the Car class. To delegate a method, do these steps:

Right-click the carEngine field in the Car class and select Source Æ Generate Delegate Methods.

In the Generate Delegate Methods dialog, select only the start method and click OK (Figure | -58).

Figure 8-58 Generate Delegate Method dialog

This action adds the start method to the Car class, and code is added in the body of the method to delegate the method call to the Engine class through the carEngine attribute.

Figure | -59 and Example | -11 shows how the HappyDriver can start the car.

Figure 8-59 Simple car example class diagram (after method delegation

Example 8-11 Car and HappyDriver class

// Car class
package itso.rad75.example;
import itso.rad75.example.Engine;
public class Car {
	private Engine carEngine = null;
	public Car(Engine carEgine) {
		this.setCarEngine(carEngine);
	}
	public Engine getCarEngine() {
		return carEngine;
	}
	private void setCarEngine(Engine carEngine) {
		if (carEngine != null) {
			this.carEngine = carEngine;
		} else {
			this.carEngine = new Engine();
		}
	}
	public void start() {
		carEngine.start();
	}
}

// HappyDriver class
package itso.rad75.example;
public class HappyDriver {
	public static void main(String[] args) {
		Car myAdvancedCar = new Car(null);
		// Start the car - I don't care about technical details
		myAdvancedCar.start();
	}
}

ibm.com/redbooks