其他工厂设计模式:
工厂设计模式入门级理解
工厂设计模式进阶(建议详细阅读)
抽象工厂设计模式
额外了解单例有助于理解
单例设计模式
背景:
1、我有一个抽象父类类且定义了泛型 暂且命名为 BaseInfo
2、我有一个接口类且定义了泛型 interface 暂且命名为 ITest
3、ITest接口存在多个实现类,且泛型均为 同时通过@Service注入到IOC中
4、BaseInfo抽象类总有个一个实例方法需要调用ITest接口的test方法
5、不同的T对应的ITest接口的实现类不同,且test方法内部逻辑不同
需求:
在泛型T动态未知的情况下,冬天的使用BaseInfo的实例方法调用到不同的ITest实现类
知识点预研:
WebApplicationContext.getBeansOfType
可以参考一下该文章的使用
最好查看一下我写的工厂设计模式
spring 的 @PostConstruct 注解使用
思路
1、在 BaseInfo 的抽象类中定义一个抽象方法:String getServiceBeanName()
每一个泛型T在继承BaseInfo时实例化该方法,返回值最好保证均不相同,最好就是对应ITest各个实现类的name
2、定义一个工厂,通过getServiceBeanName方法来来动态的获取泛型对应的具体ITest接口的实现类
代码
抽象实体类 BaseInfo
@Data
public abstract class BaseInfo{
String getServiceBeanName();
}
继承的实例类
public class TestInfo1 extends BaseInfo{
public String getServiceBeanName(){
return "ITestImpl1";
}
}
public class TestInfo2 extends BaseInfo{
public String getServiceBeanName(){
return "ITestImpl2";
}
}
定义接口
public interface ITest<T extends BaseInfo>{
void test(T t);
}
接口实现类
@Service("ITestImpl1")
public class ITestImpl1 implements ITest<TestInfo1 >{
void test(TestInfo1 t1){
//TODO
}
}
@Service("ITestImpl2")
public class ITestImpl2 implements ITest<TestInfo2 >{
void test(TestInfo2 t2){
//TODO
}
}
工厂类
@Component
public class TestFactory {
private Map<String, ITest> testMap = new HashMap<>();
@Autowired
private WebApplicationContext webApplicationContext;
public ITest getManage(String beanName) {
return testMap.get(beanName);
}
//注意这个注解
@PostConstruct
public void register() {
Map<String, ITest> map = webApplicationContext.getBeansOfType(ITest.class);
if(map != null && !map.isEmpty()){
map.entrySet().forEach(entry -> {
testMap.put(entry.getValue().getServiceBeanName(), entry.getValue());
});
}
}
}
客户端调用
public class Test{
@Autowired
private TestFactory testFactory ;
private void test1(TestInfo1 t1){
ITest itest = testFactory.getManage(t1.getServiceBeanName());
//TODO
}
}
其他工厂设计模式:
工厂设计模式入门级理解
工厂设计模式进阶(建议详细阅读)
抽象工厂设计模式
额外了解单例有助于理解
单例设计模式
根据代码来认真思考,灵活运用!
欢迎各路大神多多指点小弟