spring增强抽象工厂,反射优化

This commit is contained in:
fujiayang
2022-04-08 14:23:28 +08:00
parent a6c22cd132
commit d10845eb7e
3 changed files with 23 additions and 29 deletions

View File

@@ -6,6 +6,8 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;
@@ -15,7 +17,7 @@ import java.util.Map;
* @author F嘉阳
* @date 2022/4/8 13:42
*/
public abstract class StrategyFactory<T, S extends Strategy<T>> implements InitializingBean, ApplicationContextAware {
public abstract class AbstractStrategyFactory<T, S extends Strategy<T>> implements InitializingBean, ApplicationContextAware {
private Map<T, S> strategyMap;
@@ -31,14 +33,6 @@ public abstract class StrategyFactory<T, S extends Strategy<T>> implements Initi
return strategyMap.get(id);
}
/**
* 获取策略的类型交给子类去实现
*
* @return 策略的类型
*/
protected abstract Class<S> getStrategyType();
@Override
public void afterPropertiesSet() throws Exception {
// 获取 Spring 容器中所有 S 类型的 Bean
@@ -57,4 +51,22 @@ public abstract class StrategyFactory<T, S extends Strategy<T>> implements Initi
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
appContext = applicationContext;
}
/**
* 通过反射获取策略的类型
*
* @return 策略的类型
*/
protected Class<S> getStrategyType() {
// getClass 获取当前运行时实例的类getGenericSuperclass 获得泛型父类
Type superclass = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) superclass;
Type[] actualTypeArguments = pt.getActualTypeArguments();
// 获得索引为 1 的实际参数类型即第二个实际参数的类型
Type actualTypeArgument = actualTypeArguments[1];
@SuppressWarnings("unchecked")
Class<S> result = (Class<S>) actualTypeArgument;
return result;
}
}

View File

@@ -10,14 +10,5 @@ import top.fjy8018.designpattern.pattern.creational.factorymethod.spring.bean.Fo
* @date 2022/4/8 14:14
*/
@Component
public class FormDataHandlerFactory extends StrategyFactory<String, FormDataHandler> {
/**
* 获取策略的类型(交给子类去实现)
*
* @return 策略的类型
*/
@Override
protected Class<FormDataHandler> getStrategyType() {
return FormDataHandler.class;
}
public class FormDataHandlerFactory extends AbstractStrategyFactory<String, FormDataHandler> {
}

View File

@@ -11,14 +11,5 @@ import top.fjy8018.designpattern.pattern.creational.factorymethod.spring.bean.Fo
* @date 2022/4/8 14:17
*/
@Component
public class FormItemConverterFactory extends StrategyFactory<FormItemTypeEnum, FormItemConverter> {
/**
* 获取策略的类型(交给子类去实现)
*
* @return 策略的类型
*/
@Override
protected Class<FormItemConverter> getStrategyType() {
return FormItemConverter.class;
}
public class FormItemConverterFactory extends AbstractStrategyFactory<FormItemTypeEnum, FormItemConverter> {
}