工厂的实现

tech2022-07-15  182

工厂的实现

Bean:在计算机英语中,有可重用组件的含义 JavaBean:用Java语言编写的可用组件 JavaBean>实体类 它就是创建我们类对象的配置类 第一点:需要一个配置文件来配置我们的类 配置的类容:唯一标识:会限制类名(key,value) 第二点:通过读取配置文件中的类容:反射创建对象 位置文件xml,properties

单例:单例有线程安全问题 多例:执行效力低

单例

public class BeanFactory { public static Properties properties; //定义一个Map来存放我们要创建的对象,我们把它称之为容器 public static Map<String,Object> Beans; static { try { properties=new Properties(); InputStream in=BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"); properties.load(in); Beans=new HashMap<String, Object>(); //获取所有的键 Enumeration<Object> key=properties.keys(); while (key.hasMoreElements()){ //一次得到键名 String keys = key.nextElement().toString(); //通过键名来获取value String BeanPath = properties.getProperty(keys); //反射创建对象 Object value = Class.forName(BeanPath).newInstance(); //将key与value存放与HashMap中 Beans.put(keys,value); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } } public static Object getBean(String BeanName){ //通过Beans.get(BeanName)来获取value:com.Spring.dao.impl.IAccountDaoImpl return Beans.get(BeanName); }

多例

public class BeanFactory { public static Properties properties; static { try { properties=new Properties(); InputStream in=BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"); properties.load(in); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } } public static Object getBean(String BeanName){ Object Bean=null; try { //通过properties,的key来获取类 String BeanPath=properties.getProperty(BeanName); // Class.forName(路径名); 在学习java的反射机制的时候,首先会通过Class.forName() // 获取字节码对象, //然后再用这个对象调用newInstance()方法,创建这个类的对象,再通过对象去操作相应的字段; Bean=Class.forName(BeanPath).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return Bean; } }
最新回复(0)