一、通过调用静态工厂方法创建Bean
工厂方法:
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 ) ;
}
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 ) ;
}
Spring配置:
<
bean
id
="staticCar"
class
="factory.staticCarFactory"
factory-method
="getCar"
>
< constructor-arg value ="audi" ></ constructor-arg >
</ bean >
< constructor-arg value ="audi" ></ constructor-arg >
</ bean >
--调用静态工厂方法创建Bean是将对象创建的过程封装到静态方法中,当客户端需要对象时,只需要简单的调用静态方法,而不同关心创建对象的细节
--要声明通过静态方法创建的Bean,需要在Bean的class属性里制定拥有该工厂的方法类,同时在factory-method属性里指定工厂方法的名称。最后使用<constrctor-arg>元素为该方法传递方法参数
二、通过调用实例工厂方法创建Bean
工厂方法:
private
Map
<
String
,
Car
>
cars
=
null
;
public InstanceCarFactory (){
cars = new HashMap < String , Car > () ;
cars . put ( "audi" , new Car ( "audi" , "300000" )) ;
cars . put ( "ford" , new Car ( "ford" , "300000" )) ;
}
public Car getCar ( String name ){
return cars . get ( name ) ;
}
public InstanceCarFactory (){
cars = new HashMap < String , Car > () ;
cars . put ( "audi" , new Car ( "audi" , "300000" )) ;
cars . put ( "ford" , new Car ( "ford" , "300000" )) ;
}
public Car getCar ( String name ){
return cars . get ( name ) ;
}
Spring配置:
<!-- 配置工厂类 -->
< bean id ="carFactory" class ="factory.InstanceCarFactory" ></ bean >
<!-- 配置通过工厂创建bean -->
< bean id ="InstanceCar" factory-bean ="carFactory" factory-method ="getCar" >
< constructor-arg value ="ford" ></ constructor-arg >
</ bean >
< bean id ="carFactory" class ="factory.InstanceCarFactory" ></ bean >
<!-- 配置通过工厂创建bean -->
< bean id ="InstanceCar" factory-bean ="carFactory" factory-method ="getCar" >
< constructor-arg value ="ford" ></ constructor-arg >
</ bean >
--实例工厂方法:将对象的创建过程封装到另外一个对象实例的方法里,当客户端需要请求对象时,只需要简单的调用该实例方法而不需要关心对象的创建细节。
--要声明通过实例工厂方法创建的Bean
--在bean的factory-bean属性里指定拥有该工厂方法的Bean
--在factory-method属性里指定该工厂方法的名称
--使用constructor-arg元素为工厂方法传递方法参数