通过调用静态工厂方法创建Bean
调用静态工厂方法创建Bean是将对象创建的过程封装到静态方法中,当客户端需要对象时,只需要简单地调用静态方法,而不同关心创建对象的细节
要声明通过静态方法创建Bean,需要在Bean的class属性里指定拥有该工厂的方法的类,同时在factory-method属性里指定工厂方法的名称,最后,使用<constrctor-arg>元素为该方法传递方法参数
代码语言:javascript复制// Car
public class Car {
private String brand;
private double price;
public Car(String brand, double price){
this.brand = brand;
this.price = price;
}
public void setBrand(String brand) {
this.brand = brand;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
public String getBrand() {
return brand;
}
@Override
public String toString() {
return "Car{"
"brand='" brand '''
", price=" price
'}';
}
public Car(){
System.out.println("car's constructor");
}
}
// Main
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car =(Car) ctx.getBean("car");
System.out.println(car);
}
}
// StaticCarFactory
public class StaticCarFactory {
private static Map<String,Car> cars = new HashMap<String,Car>();
static {
cars.put("audi",new Car("audi",300000));
cars.put("ford",new Car("ford",400000));
}
public static Car getCar(String name){
return cars.get(name);
}
}
// XML
<!-- 通过静态工厂方法来配置bean。注意不是配置静态工厂方法实例,而是配置bean实例-->
<!-- class 属性:指向静态工厂方法的全类名-->
<!-- factory-method:指向静态工厂方法的名字 -->
<!-- constructor-arg:如果工厂方法需要传入参数,则使用constructor-arg来配置参数 -->
<bean id="car" class="com.sangyu.test04.StaticCarFactory" factory-method="getCar">
<constructor-arg value="audi"></constructor-arg>
</bean>
通过调用实例工厂方法创建Bean
实例工厂方法:将对象的创建过程封装到另外一个对象实例的方法里,当客户端需要请求对象时,只需要简单的调用该实例方法而不需要关心对象创建细节
代码语言:javascript复制// StaticCarFactory
public class StaticCarFactory {
private static Map<String,Car> cars = new HashMap<String,Car>();
static {
cars.put("audi",new Car("audi",300000));
cars.put("ford",new Car("ford",400000));
}
public static Car getCar(String name){
return cars.get(name);
}
}
// XML
<bean id="carFactory" class="com.sangyu.test04.InstanceCarFactory"></bean>
<bean id="car" factory-bean="carFactory" factory-method="getCar">
<constructor-arg value="ford"></constructor-arg>
</bean>