Java Reference
In-Depth Information
Factory Helper
The factory helper is a common and widely used dependency injection strategy. It is
based on the GOF factory method design pattern. The factory method consolidates the
use of the new operator and supplies appropriate object instances based on some input.
This is shown in Listing 2-2.
Listing 2-2. : Using Factory Helper
public class FormulaOneDriver{
public Car getCar(){
Car car = CarFactory.getInstance("FERARI");
return car;
Using a factory promotes an object design best practice called program to interface
(P2I). This principle states that concrete objects must implement an interface that is used
in the caller program rather than the concrete object itself. Therefore, you can easily
substitute a different implementation with little impact on client code. In other words,
there is no direct dependency on the concrete implementation leading to low coupling.
Listing 2-3 shows the Car interface.
Listing 2-3.
public interface Car{
public Color getColor();
//other methods
The FerrariCar provides a concrete implementation of the Car interface, as shown in
Listing 2-4.
Listing 2-4.
public class FerrariCar implements Car{
//...implementation of methods defined in Car
// ...implementation of other methods
Search WWH ::

Custom Search