其中模拟的过程中使用到一个别的技术:解析xml文件。这个可以自己去网上搜一下JDOM、不在这里解释。上网看一下、很快就能上手用。
1、 建立spring的配置文件、就放在com.chy.spring.factory包下――applicationContext.xml:
2、 创建BeanFactory:
package com.chy.spring.factory;
public interface BeanFactory {
public Object getBean(String id);
}
3、 创建BeanFactory的子类――ClassPathXmlApplicationContext:
package com.chy.spring.factory;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
public class ClassPathXmlApplicationContext implements BeanFactory {
//用于存放生成的bean的实例
private Map
map = new HashMap
(); /** * 在构造方法中解析applicationContext.xml、并存放到Map中 * @param fileName * @throws Exception */ public ClassPathXmlApplicationContext(String fileName) throws Exception { SAXBuilder builder = new SAXBuilder(); InputStream file = this.getClass().getClassLoader().getResourceAsStream(fileName); Document document = builder.build(file);// 获得文档对象 Element root = document.getRootElement();// 获得根节点 List
list = root.getChildren(); System.out.println(list.size()); for(Element e : list){ String id = e.getAttributeva lue("id"); String clazz = e.getAttributeva lue("class"); Object o = Class.forName(clazz).newInstance(); map.put(id, o); } } /** * 提供获取bean的一个方法。 */ @Override public Object getBean(String id) { return map.get(id); } }
4、 将上面的Car、Moveable复制一份下来。
5、 配置applicationContext.xml如第一步中写好的。
6、 在Client中使用:
package com.chy.spring.factory;
import java.util.Properties;
public class Client {
public static void main(String[] args) throws Exception {
springContextMehtod();
}
/**
* 模拟spring的bean工厂来实现通过工厂获取bean实例
* @throws Exception
*/
private static void springContextMehtod() throws Exception {
BeanFactory factory = new ClassPathXmlApplicationContext("com/chy/spring/factory/applicationContext.xml");
Object o = factory.getBean("v");
Moveable m = (Moveable)o;
m.run();
}
/**
* 模拟读取资源文件来实例化指定的bean。
* @throws Exception
*/
@SuppressWarnings("unused")
private static void propertiesMethod() throws Exception{
// 加载资源文件、获取资源文件中指定名称的值。
Properties props = new Properties();
props.load(Client.class.getClassLoader().getResourceAsStream(
"com/chy/spring/factory/spring.properties"));
String vehicleType = props.getProperty("VehicleType");
// 使用Class.forName(String className)将这个类的class文件load到内存中
// 再使用newInstance实例化这个类。
Object o = Class.forName(vehicleType).newInstance();
Moveable m = (Moveable) o;
m.run();
}
}
七:总结与补充
1、总结:
工厂是一个系列的设计模式。静态工厂、简单工厂(或者称为普通工厂)、抽象工厂。在实际的设计中、并不会仅仅的时候一种设计模式、只有更合适的设计模式、没有最合适的设计模式。spring最重要的两个特性IOC、AOP。从上面对BeanFactory的模拟也可以看出一点IOC的特性、就是使用工厂模式来帮我们生产bean。AOP则是动态代理设计模式的一个应用。最后提一句没有一种框架是没有用到反射的!
2、补充:
抽象工厂中使用的JavaBean可以自己构建、没有全部贴出来、完全可以定义一个抽象类(代表的是一类的事务、当然你也可以使用接口)、最后一个Client中贴的第二个方法简单的补充一下:是通过读取资源文件中配置信息来实例化Bean。这也意味着在实际项目中我们可以在项目已经完成之后可以动态的通过配置文件(Java代码已经被编译成class文件了)来指定我们想要的处理方式。
3、结构图:

更多内容:Java设计模式之起始