zoukankan      html  css  js  c++  java
  • javaWeb项目解耦之工厂模式使用

    javaWeb项目使用经典三层架构

    config.properties 文件配置如图所示

    factory代码

    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.Reader;
    import java.util.Properties;
    
    public class BaseFactory {
        private static BaseFactory factory = new BaseFactory();
        private static Properties prop = null;
        private BaseFactory() {
        }
        public static BaseFactory getFactory(){
            return factory;
        }
        
        static{
            try {
                prop = new Properties();
                prop.load(new FileReader(BaseFactory.class.getClassLoader().getResource("config.properties").getPath()));
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        public <T> T getInstance(Class<T> clazz){
            try {
                String cName = clazz.getSimpleName();
                String cImplName = prop.getProperty(cName);
                return (T)Class.forName(cImplName).newInstance();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            
        }
        
    }


    service调用dao层 示例代码

     UserDao userDao = BaseFactory.getFactory().getInstance(UserDao.class);

  • 相关阅读:
    字典
    字符串常用的方法
    切片,集合、文件处理
    蓝桥杯练习 Day6 题解
    spoj-ORDERS
    spoj-SUBSUMS
    spoj
    spoj --- ABCDEF
    C. Andryusha and Colored Balloons
    B. The Meeting Place Cannot Be Changed
  • 原文地址:https://www.cnblogs.com/majiabin/p/4731505.html
Copyright © 2011-2022 走看看