1. 程式人生 > >java實現解耦小案例

java實現解耦小案例

簡單地說,軟體工程中物件之間的耦合度就是物件之間的依賴性。指導使用和維護物件的主要問題是物件之間的多重依賴性。物件之間的耦合越高,維護成本越高。因此物件的設計應使類和構件之間的耦合最小。

檔案結構
這裡寫圖片描述

Dao

public interface IAccountDao {
    void saveAccount();
}

DaoImpl

public class AccountDaoImpl implements IAccountDao {
    public void saveAccount() {
        System.out.println("賬戶儲存實現了");
    }
}

Service

public interface IAccountService {
    void saveAccount();
}

ServiceImpl

public class AccountServiceImpl implements IAccountService {
    //private IAccountDao accountDao = new AccountDaoImpl();
    //使用反射方式,替代直接呼叫AccountDaoImpl
    private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");
    public void saveAccount() {
        accountDao.saveAccount();
    }
}

表現層Client

public class Client {
    public static void main(String[] args) {
        //IAccountService accountService = new AccountServiceImpl();
        IAccountService accountService = (IAccountService)BeanFactory.getBean("accountService");
        accountService.saveAccount();
    }
}

工廠BeanFactory

public class BeanFactory {
    //讀取配置檔案
    private static Properties properties;

    //定義一個容器map,用於存放我們要建立的物件
    //單例模式
    private 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> keys = properties.keys();
            //遍歷列舉
            while (keys.hasMoreElements()) {
                //取出每一個key
                String key = keys.nextElement().toString();
                //通過key獲取value(全限定類名)
                String beanPath = properties.getProperty(key);
                //反射建立物件
                Object value = Class.forName(beanPath).newInstance();
                //存入容器map
                beans.put(key, value);
            }
        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化properties失敗!");
        }
    }

    /**
     * 根據Bean的名稱獲取bean物件
     * 單例模式
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {

        return beans.get(beanName);
    }



    ///**
    // * 根據Bean的名稱獲取bean物件
    // * 多例模式
    // * @param beanName
    // * @return
    // */
    //public static Object getBean(String beanName) {
    //    Object bean = null;
    //    try {
    //        String beanPath = properties.getProperty(beanName);
    //        bean = Class.forName(beanPath).newInstance();
    //    } catch (Exception e) {
    //        e.printStackTrace();
    //    }
    //    return bean;
    //
    //}
}

配置檔案bean.properties

accountService=com.ouyang.service.impl.AccountServiceImpl
accountDao=com.ouyang.dao.impl.AccountDaoImpl