Using static factory method

We can define a static method in the class that returns the object. The attribute factory-method is used to specify the method name which does instance creation. Let's use the Ch02_Instance_Creation project to use a factory-method attribute with the help of the following steps:

  1. Create a CarService class in the com.ch02.service package, as shown in the following piece of code:
public class CarService { 
  private static CarService carService=new CarService(); 
 
  private CarService(){} 
 
  public static CarService createService() 
  { 
    return carService; 
  } 
  public void serve() 
  { 
    System.out.println("car service"); 
  } 
} 
  1. Add the configuration in XML as follows:
<bean id="carService" factory-method="createService" 
class="com.ch02.service.CarService"/> 

The factory-method attribute specifies the method that returns the instance.

  1. Write the test code in Test_CarService as follows:
public static void main(String[] args) { 
  // TODO Auto-generated method stub 
  ApplicationContext context = new 
    ClassPathXmlApplicationContext("instance.xml"); 
  CarService carService= (CarService) 
  context.getBean("carService"); 
  carService.serve(); 
} 

The execution of the code gives the following output, as shown in the following screenshot:

Once the instance is created, now it's time to initialize the state. The Java developers' initialization state is as follows:

car.setChassis_number("as123er"); 
car.setColor("baker's chocolate"); 
car.setFuel_Type("Petrol"); 
car.setPrice(689067L); 
car.setAverage(21); 

Here, if we change the values of the data members, the state also gets changed. So, it's pretty clear that the car is dependent on data member values. However, here, as we have set them, the values are part of the code, and any change in them needs a change in the code or redeployment of the code. In Dependency injection, the design is done in such a way that the object achieves its state externally instead of hard coding them from a piece of the code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.42.196