工厂的实现
 
Bean:在计算机英语中,有可重用组件的含义 JavaBean:用Java语言编写的可用组件 JavaBean>实体类 它就是创建我们类对象的配置类 第一点:需要一个配置文件来配置我们的类 配置的类容:唯一标识:会限制类名(key,value) 第二点:通过读取配置文件中的类容:反射创建对象 位置文件xml,properties
 
单例:单例有线程安全问题 多例:执行效力低
 
单例
 
public class BeanFactory {
    public static Properties properties
;
    
    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();
               
               String BeanPath 
= properties
.getProperty(keys
);
               
                Object value 
= Class
.forName(BeanPath
).newInstance();
                
                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
){
    
        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 {
        
            String BeanPath
=properties
.getProperty(BeanName
);
            
            
            
            Bean
=Class
.forName(BeanPath
).newInstance();
        } catch (InstantiationException e
) {
            e
.printStackTrace();
        } catch (IllegalAccessException e
) {
            e
.printStackTrace();
        } catch (ClassNotFoundException e
) {
            e
.printStackTrace();
        }
        return Bean
;
    }
}
                
                
                
        
    
转载请注明原文地址:https://tech.qufami.com/read-842.html