定义:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。
工厂方法模式 基本代码
interface IProduct {
public void productMethod();
}
class Product implements IProduct {
public void productMethod() {
System.out.println("产品");
}
}
interface IFactory {
public IProduct createProduct();
}
class Factory implements IFactory {
public IProduct createProduct() {
return new Product();
}
}
public class Client {
public static void main(String[] args) {
IFactory factory = new Factory();
IProduct prodect = factory.createProduct();
prodect.productMethod();
}
}
业务场景
工厂模式是一个用于实例化对象的模式,是用工厂方法代替new操作的一种方式。工厂模式在Java项目中到处都是,因为工厂模式就相当于创建实例对象的new,如在我们的系统中经常需要记日志,如果创建logger实例时所做的初始化工作可能是很长一段代码,可能要初始化、赋值、查询数据等等,则会导致代码臃肿而难看
private static Logger logger = LoggerFactory.getLogger(MyBusinessRPC.class);
logger.error("数据查询失败,table" + ...);
//源码分析
public static Logger getLogger(String name) {
ILoggerFactory iLoggerFactory = getILoggerFactory();
return iLoggerFactory.getLogger(name);
}
//源码分析
public static ILoggerFactory getILoggerFactory() {
if (INITIALIZATION_STATE == UNINITIALIZED) {
INITIALIZATION_STATE = ONGOING_INITIALIZATION;
performInitialization();
}
switch (INITIALIZATION_STATE) {
case SUCCESSFUL_INITIALIZATION:
return StaticLoggerBinder.getSingleton().getLoggerFactory();
case NOP_FALLBACK_INITIALIZATION:
return NOP_FALLBACK_FACTORY;
case FAILED_INITIALIZATION:
throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
case ONGOING_INITIALIZATION:
// support re-entrant behavior.
// See also http://bugzilla.slf4j.org/show_bug.cgi?id=106
return TEMP_FACTORY;
}
throw new IllegalStateException("Unreachable code");
}
业务场景
比如我们要从集合(库存中)中取出一个数据,或者一些调度算法,我们有很策略实现(先进先出,最少使用,最近最少使用,最近最少使用 等)
public class ArithmeticFactory {
public Arithmetic createFiFoArithmetic(){
Arithmetic arithmetic = new FIFOStockArithmetic();
return arithmetic;
}
public Arithmetic createNoUseArithmetic(){
Arithmetic arithmetic = new NoUseStockArithmetic();
return arithmetic;
}
} public interface Arithmetic {
public void invoke();
} public class FIFOStockArithmetic implements Arithmetic {
@Override
public void invoke() {
System.out.println("使用了先进先出算法!");
//具体算法的业务逻辑
}
} public class NoUseStockArithmetic implements Arithmetic {
@Override
public void invoke() {
System.out.println("使用了最少使用算法!");
//具体算法的业务逻辑
}
}
测试 结果
public class FactoryTest {
public static void main(String args[]){
ArithmeticFactory arithmeticFactory = new ArithmeticFactory();
Arithmetic fiFoArithmetic = arithmeticFactory.createFiFoArithmetic();
Arithmetic noUserarithmetic = arithmeticFactory.createNoUseArithmetic();
fiFoArithmetic.invoke();
noUserarithmetic.invoke();
}
}
业务场景
spring 和 mybatis 的sqlSessonFactory
<!-- 配置集成Mybatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/config/SQLMapConfig.xml" />
<property name="mapperLocations" value="classpath*:com/*/*/**/infra/mybatis/*Mapper.xml"/>
</bean>
<bean id="simpleTempalte" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
<constructor-arg index="1" value="SIMPLE"/>
</bean>
<bean id="batchTempalte" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
<constructor-arg index="1" value="BATCH"/>
</bean>