最近使用 MVC 模式實在是不能自拔,同時也致使出現一列的問題:高耦合。
每一個程序猿談到程序如何設計纔好的時候,基本上張嘴就來:高併發、低耦合、高內聚......
那麼問題來了,什麼是耦合?如何實現低耦合?
耦合就是對模塊間關聯程度的度量。簡單來講就是個程序之間的依賴程度,包括類之間的依賴、函數之間的了依賴。
咱們有這麼一個場景,須要實現一個帳戶保存的功能。這個很簡單,無非就是兩個接口、兩個實現類、再加一個測試類的事情。
Talk is cheap, show me the code;
public interface IAccountDao { /** * 保存帳戶 */ void saveAccount(); }
public class AccountDaoImpl implements IAccountDao { @Override public void saveAccount() { System.out.println("已保存帳戶~!"); } }
public interface IAccountService { /** * 保存帳戶 */ void saveAccount(); }
public class AccountServiceImpl implements IAccountService { /** * 持久層對象 */ private IAccountDao accountDao = new AccountDaoImpl(); @Override public void saveAccount() { accountDao.saveAccount(); } }
public class AccountDemo { public static void main(String[] args) { IAccountService as = new AccountServiceImpl(); as.saveAccount(); } } // 如下爲輸出結果 已保存帳戶~!
那麼咱們剛剛說的低耦合,在上面的這幾段代碼中,耦合程度是很高的。爲啥說高耦合呢,倘若咱們不當心刪了 AccountDaoImpl ,整個程序都沒法經過編譯(如圖)。那麼這時候就須要解耦。
這時候咱們的工廠模式也就出來了。
在實際開發中,耦合是必然存在的,故只能儘可能下降依賴,不能消除。
通常的解耦的思路:java
使用配置文件能夠達到一個目的,就是當咱們經過一些固定不變的內容,能夠把其抽取出單獨保存,經過調用的方式獲取其實例(跟常量類的方式無異)。
accountService=wiki.laona.service.impl.AccountServiceImpl accountDao=wiki.laona.dao.impl.AccountDaoImpl
/** * @description: Bean對象的工廠模式 * @author: laona **/ public class BeanFactory { /** * Properties 對象 */ private static Properties props; /** * 靜態代碼塊爲 Properties 對象賦值 */ static { try { // 實例化對象 props = new Properties(); // 獲取 properties 文件的流對象 InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"); props.load(in); } catch (IOException e) { throw new ExceptionInInitializerError("初始化 properties 文件異常!"); } } /** * 獲取對象實例 * @param beanName 對象實例名 * @return {@link Object} 對象實例 */ public static Object getBean(String beanName) { Object bean = null; try { String beanPath = props.getProperty(beanName); bean = Class.forName(beanPath).newInstance(); }catch (Exception e) { e.printStackTrace(); } return bean; } }
public class AccountServiceImpl implements IAccountService { // 經過工廠模式獲取 AccountDaoImpl 的實例 private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao"); @Override public void saveAccount() { accountDao.saveAccount(); } }
public class AccountDemo { public static void main(String[] args) { // IAccountService as = new AccountServiceImpl(); IAccountService as = (AccountServiceImpl) BeanFactory.getBean("accountService"); as.saveAccount(); } }
這樣整個包結構就變成了這樣:
![]()
耦合只是相對而言,工廠模式也不是完美的,仍然存在不少能夠優化的地方,可是能夠減小部分耦合就是對程序性能的一個大幅度的提高。