一:静态工厂方法
1.调用静态工厂方法创建Bean是将对象创建Bean的创建过程封装到静态方法中,当客户端需要对象时,只需要简单的调用静态方法,而不关心创建对象的细节。
2.要声明通过静态方法创建的Bean,需要在Bean的class属性里指定拥有该工厂方法的类,同时在factory-method属性里指定工厂方法的名称,最后使用constructor-arg元素为该方法传递参数。
二:代码实现
1.创建一个Car类
package com.dhx.factory;
public class Car {
private String brand;
private double price;
public Car(String brand, double price) {
super();
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
}
2.创建静态工厂
package com.dhx.factory;
import java.util.HashMap;
import java.util.Map;
/**
* 静态工厂方法:直接调用某一个类的静态方法就可以返回Bean的实例
* @author Administrator
*
*/
public class StaticCarFactory {
private static Map<String,Car> cars=new HashMap<String,Car> ();
static {
cars.put("audi", new Car("audi", 30000));
cars.put("baoma", new Car("baoma", 40000));
}
//静态工厂方法
public static Car getCar(String name) {
return cars.get(name);
}
}
3.配置XML文件(beans-factory.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--通过静态工厂方法来配置Bean,注意不是配置静态工厂方法实例,而是配置Bean实例 -->
<!--
class属性:指向静态工厂方法的全类名
factory-method:指向静态工厂方法的名字
constructor-arg:如果工厂方法需要传入参数,则使用constructor-arg来传递参数
-->
<bean id="car"
class="com.dhx.factory.StaticCarFactory"
factory-method="getCar">
<constructor-arg value="baoma"></constructor-arg>
</bean>
</beans>
4.测试
package com.dhx.factory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-factory.xml");
Car car=(Car) ctx.getBean("car");
System.out.println(car);
}
}