工厂模式的定义:工厂帮我们创建对象,有一个专门帮我们创建对象的类,这个类就是工厂。
首先工厂模式分为了静态工厂和动态工厂两种,静态工厂是无需本身创建对象注入到IOC容器中,而动态工厂则反之,然后我们来看看模式的建立过程。
静态工厂
工厂本身不用创建对象,通过静态方法调用,对象=工厂类.方法名
/**
* 静态工厂
*/
public class AirPlaneStaticFactory {
public static AirPlane getAirPlane(String jz){
System.out.println("静态工厂===========在造飞机");
AirPlane airPlane = new AirPlane();
airPlane.setJz(jz);
airPlane.setFdj("太行");
airPlane.setPersonNum(300);
airPlane.setYc("198m");
return airPlane;
}
}
在applicationContext.xml中创建
factory-method:指定这个工厂中哪个方法是工厂方法
<bean id="airPlane01" class="cn.why.factory.AirPlaneStaticFactory"
factory-method="getAirPlane" >
<constructor-arg name="jz" value="张三"></constructor-arg>
</bean>
实例工厂
工厂本身需要创建对象
/**
* 实例工厂
*/
public class AirPlaneInstanceFactory {
public AirPlane getAirPlane(String jz){
System.out.println("实例工厂===========在造飞机");
AirPlane airPlane = new AirPlane();
airPlane.setJz(jz);
airPlane.setFdj("太行");
airPlane.setPersonNum(300);
airPlane.setYc("198m");
return airPlane;
}
}
在applicationContext.xml中创建
factory-bean:指定使用哪个工厂实例
<bean id="airPlaneInstanceFactory"
class="cn.why.factory.AirPlaneInstanceFactory">//实例化工厂
</bean>
<bean id="airPlane02" class="cn.why.bean.AirPlane"
factory-bean="airPlaneInstanceFactory"
factory-method="getAirPlane">
<constructor-arg value="李四"/>
</bean>
通过FactoryBean接口创建工厂
同样Spring也为我们创建了一个接口FacyoryBean,而只要实现了这个接口,Spring都会认为其为一个工厂,该接口也拥有如下属性:
1.IOC容器启动时不会创建实例;
2.FactoryBean只要获取的时候才创建对象;
我们来写一个实现类
**
*实现了FactoryBean接口的类是Spring可以认识的工厂类,
* Spring会自动的调用工厂方法来创建实例
*
* 1.编写一个FactoryBean的实现类
* 2.在Spring配置文件中进行注册
*/
public class MyFactoryBeanImple implements FactoryBean<Book> {
/**
* 返回构建的对象
* @return
* @throws Exception
*/
@Override
public Book getObject() throws Exception {
System.out.println("我来帮你========创建对象");
Book book = new Book();
book.setBookname(UUID.randomUUID().toString());
return book;
}
/**
* 返回创建的对象的类型
* spring会调用该方法来确认创建的对象是什么类型
* @return
*/
@Override
public Class<?> getObjectType() {
return Book.class;
}
/**
* isSingleton 是单例?
* false 不是
* true 是
* @return
*/
@Override
public boolean isSingleton() {
return false;
}
}
最后在简单的注入到IOC容器中,便可实现。