1. 程式人生 > >JDBC使用Dao工廠模式讀取properties配置檔案實現解耦

JDBC使用Dao工廠模式讀取properties配置檔案實現解耦

daoconfig.properties配置檔案內容:

userDaoClass=com.ls.www.dao.impl.UserDaoImpl

測試類

package com.ls.www.dao;

import com.ls.www.domain.User;

public class UserDaoTest {
    public static void main(String[] args) {
    UserDao userDao=DaoFactory.getInstance().getUserDao();

    User user=userDao.getUser(4);
    userDao.delete(user);
    }
}


簡單工廠類:

package com.ls.www.dao;

import  java.io.InputStream;
import  java.util.Properties;

public class DaoFactory {
    private UserDao userDao=null;
    //使用單例模式
    private static DaoFactory instance=new DaoFactory();
    private DaoFactory() {
    try {
        Properties prop=new Properties();
        InputStream in =DaoFactory.class.getClassLoader()
                        .getResourceAsStream("daoconfig.properties");
        prop.load(in);
        String userDaoClassName=
        prop.getProperty("userDaoClass");
        userDao=(UserDao)Class.forName(userDaoClassName).newInstance();
    } catch (Exception e) {
        throw new ExceptionInInitializerError(e);
    }
}
    public static DaoFactory getInstance(){
        return instance;
    }
    public UserDao getUserDao(){
        return userDao;
    }
}


Dao介面

package com.ls.www.dao;

import com.ls.www.domain.User;

public interface UserDao {
    public abstract void addUser(User user);

    public abstract User getUser(int id);

    public abstract User findUser(String loginName,String password);

    public abstract void update(User user);

    public abstract void delete(User user);

}

通過以上程式碼可發現:我們的程式是面向介面程式設計的,所有程式碼中沒有一個new關鍵字,也就是說測試類不依賴於介面的具體實現,從而實現解耦。以後如果具體實現有變化,只需在配置檔案中的value(等號右邊)修改為對應的全限定名。