目录
工厂模式为我们提供选择动态实现类的灵活性,那么,在Spring框架内,怎么实现工厂模式呢?
1. 设计接口
public interface Courier {
public String deliver(String items, String address);
}
2. 设计实现类
package com.sdp.component;
@Service
public class BlueDart implements Courier {
public String deliver(String iteams, String address) {
return iteams+ "Shiped to Address "+address +"Through BlueDart";
}
}
package com.sdp.component;
@Service
public class Dtdc implements Courier {
public String deliver(String iteams, String address) {
return iteams+ "Shiped to Address "+address +"Through Dtdc";
}
}
方式一:自定义工厂类
@Service
public class Factory{
@Autowired
private List<Courier> couriers;
public Courier create(String type){
return couriers.filter(s->s.getName().equals("type"));
}
}
方式二:通过AbstractFactoryBean实现
1. 继承AbstractFactoryBean,实现对应的方法
public class ExampleFactoryBean extends AbstractFactoryBean<Courier> {
@Override
public Class<?> getObjectType() {
return Courier.class;
}
@Override
protected Courier createInstance() throws Exception {
if(xxx){
return xxx;
}else if(yyy){
return yyy;
}
}
}
2. 通过JavaConfig的方式,注册为Bean
@Configuration
public class ExampleConfig {
@Bean
public FactoryBean<Courier> courier() {
return new ExampleFactoryBean();
}
}
3. 获取Bean
AbstractApplicationContext context = new AnnotationConfigApplicationContext(ExampleConfig.class);
Courier courier = (Courier) context.getBean("courier");
4. 获取FactoryBean
// 在Bean名称前添加"&"
FactoryBean<Courier> bean = (FactoryBean<Courier>) context.getBean("&courier");
5. 默认情况下,是singleton,可以复写方法修改为prototype
@Override
public boolean isSingleton() {
return false;
}