Spring Framework Development IOC Two Ways to Create Factory Detailed Explanation

  • 2021-11-13 07:53:32
  • OfStack

1. IOC has two ways to create a factory

IoC creates bean through factory mode in two ways: static factory method instance factory method

2. Differences between the two approaches

2.1 Static Method Creation

That is, you can instantiate an object directly through a static method, and create it in the way of class name and method name


public class HelloFactory {
    public static HelloWorld getInstance(){
        return new Hello();
    }
}
HelloWorldFactory.getInstance();
 

2.2 Instance Method Creation

Using new to open up heap memory


public class Hello {
    public HelloWorld createHelloWorld(){
        return new Hello();
    }
}
Hello helloF = new Hello();
hello.createHelloWorld();

Static factory method


package entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
 private long id;
 private String name;
}
 
package factory;
import entity.Car;
import java.util.HashMap;
import java.util.Map;
public class StaticCarFactory {
 private static Map<Long, Car> carMap;
 static{
 carMap = new HashMap<Long, Car>();
 carMap.put(1L,new Car(1L," Treasure ⻢"));
 carMap.put(2L,new Car(2L," Mercedes-Benz "));
 }
 public static Car getCar(long id){
 return carMap.get(id);
 }
}

xml Configuration File


<!--  Configure static ⼯⼚ Create  Car -->
<bean id="car" class="com.southwind.factory.StaticCarFactory" factorymethod="getCar">
 <constructor-arg value="2"></constructor-arg>
</bean>

Instance factory creation


package factory;
import entity.Car;
import java.util.HashMap;
import java.util.Map;
public class InstanceCarFactory {
 private Map<Long, Car> carMap;
 public InstanceCarFactory(){
 carMap = new HashMap<Long, Car>();
 carMap.put(1L,new Car(1L," Treasure ⻢"));
 carMap.put(2L,new Car(2L," Mercedes-Benz "));
 }
 public Car getCar(long id){
 return carMap.get(id);
 }
}

xml Configuration File


<!--  Configuration instance ⼯⼚ bean -->
<bean id="carFactory" class="factory.InstanceCarFactory">
</bean>
<!--  Examples of compensation ⼯⼚ Create  Car -->
<bean id="car2" factory-bean="carFactory" factory-method="getCar">
 <constructor-arg value="1"></constructor-arg>
</bean>

Summarize

The idea of factory mode is just in line with the design idea of SpringIOC: the selection control right of the specific implementation class of a 1 interface is removed from the calling class and handed over to the third party for decision, that is, the control is realized by Bean configuration of Spring, which is also the idea of factory mode. It fully embodies the characteristics of decoupling and easy maintenance.

The above is the Spring framework IOC two ways to create a factory details, more about Spring framework IOC to create a factory information please pay attention to other related articles on this site!


Related articles: