1、定义
由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类。
2、Spring实例
BeanFactory就是简单工厂模式的体现,根据传入一个唯一的标识来获得bean对象,但是在传入参数后创建还是传入参数前创建,这个要根据具体情况来定。
模拟BeanFactory实例化一个Bean:
public interface BeanFactory {
Object getBean(String id) throws ExecutionException;
}
public class ClassPathXmlApplicationContext implements BeanFactory {
private Map<String, Object> map = new HashMap<String, Object>();
@SuppressWarnings("unchecked")
public ClassPathXmlApplicationContext(String fileName)
throws DocumentException, InstantiationException, IllegalAccessException, ClassNotFoundException {
// 加载配置文件
SAXReader reader = new SAXReader();
Document document = reader
.read(ClassPathXmlApplicationContext.class.getClassLoader().getResourceAsStream(fileName));
// 获取根节点
Element root = document.getRootElement();
// 获取子节点
List<Element> childElements = root.elements();
for (Element element : childElements) {
map.put(element.attributeValue("id"), Class.forName(element.attributeValue("class")).newInstance());
}
}
@Override
public Object getBean(String id) throws ExecutionException {
return map.get(id);
}
}
public class Car {
public void run() {
System.out.println("这是一辆汽车...");
}
}
public class Train {
public void run() {
System.out.println("这是一辆火车....");
}
}
配置XML文件:
<beans>
<bean id="car" class="factory.Car">
</bean>
<bean id="train" class="factory.Train">
</bean>
</beans>
测试:
public class BeanFactoryTest {
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
ClassNotFoundException, DocumentException, ExecutionException {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("factory/applicationContext.xml");
Car car = (Car) beanFactory.getBean("car");
car.run();
Train train = (Train) beanFactory.getBean("train");
train.run();
}
}
输出:
这是一辆汽车...
这是一辆火车....