程序的耦合java
耦合:程序間的依賴關係spa
包括:code
類之間的依賴xml
方法間的依賴對象
解耦:blog
下降程序間的依賴關係開發
在實際開發中:get
應該作到,編譯期不依賴,運行時才依賴it
解耦思路:io
第一步:使用反射來建立對象,而避免使用new關鍵詞
第二步:經過讀取配置文件來獲取要建立的對象全限定類名
1 /** 2 * 一個建立Bean對象的工廠 3 * 4 * Bean:在計算機英語中,有可重用組件的含義 5 * JavaBean:用java語言編寫的可重用組件 6 * javabean > 實體類 7 * 8 * 它就是建立咱們的service的dao對象的 9 * 第一個:須要一個配置文件來配置咱們的service和dao 10 * 配置的內容:惟一標識=全限定類名 11 * 第二個:經過讀取配置文件中配置的內容,反射建立對象 12 * 13 * 配置文件能夠是xml也能夠是properties 14 * 15 */ 16 public class BeanFactory { 17 18 //定義一個Properties對象 19 private static Properties props; 20 21 //使用靜態代碼塊爲Properties對象賦值 22 static { 23 try { 24 //實例化對象 25 props = new Properties(); 26 //獲取properties文件的流對象,建立在resources文件夾下的properties文件會成爲類根路徑下的文件,不用寫包名 27 InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"); 28 props.load(in); 29 } catch (Exception e) { 30 throw new ExceptionInInitializerError("初始化properties失敗"); 31 } 32 } 33 34 /** 35 * 根據Bean的名稱獲取bean對象 36 * @param beanName 37 * @return 38 */ 39 public static Object getBean(String beanName){ 40 Object bean = null; 41 try{ 42 String beanPath = props.getProperty(beanName); 43 System.out.println(beanPath); 44 bean = Class.forName(beanPath).newInstance(); 45 }catch (Exception e){ 46 e.printStackTrace(); 47 } 48 return bean; 49 } 50 51 }
調用BeanFactory,反射建立對象
1 /** 2 * 帳戶業務層實現類 3 */ 4 public class AccountServiceImpl implements IAccountService { 5 6 //private IAccountDao accountDao = new AccountDaoImpl(); 7 private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao"); 8 9 public void saveAccount(){ 10 accountDao.saveAccount(); 11 } 12 }
1 /** 2 * 模擬一個表現層,用於調用業務層 3 */ 4 public class Client { 5 6 public static void main(String[] args) { 7 // IAccountService accountService = new AccountServiceImpl(); 8 IAccountService accountService = (IAccountService) BeanFactory.getBean("accountService"); 9 accountService.saveAccount(); 10 } 11 }