package com.gus.factory; import java.io.FileReader; import java.util.Properties; public class BasicFactory { private static BasicFactory basicFactory = new BasicFactory(); private static Properties properties; private BasicFactory(){} public BasicFactory getBasicFactory() { return basicFactory; } static { properties = new Properties(); try { properties.load(new FileReader(BasicFactory.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 = properties.getProperty(cName); return (T)Class.forName(cImplName).newInstance(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } } //在ServiceImpl中只須要這麼寫: //CustomerDao customerDao = BasicFactory.getBasicFactory().getInstance(CustomerDao.class);
通常的實現解耦的工廠類:java
package com.gus.factory; import com.gus.dao.CustomerDao; import java.io.FileReader; import java.util.Properties; //單例模式,須要對外提供方法 //這個工廠提供了dao層和service的解耦 public class CustomerDaoFactory { private static CustomerDaoFactory customerDaoFactory = new CustomerDaoFactory(); private static Properties properties = null; private CustomerDaoFactory() { } public static CustomerDaoFactory getCustomerFactory() { return customerDaoFactory; } // 讀取配置文件 static { properties = new Properties(); try { properties.load(new FileReader(CustomerDaoFactory.class.getClassLoader().getResource("config.properties").getPath())); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } public CustomerDao getCustomerDao() { String clazz = properties.getProperty("CustomerDao"); try { return (CustomerDao) Class.forName(clazz).newInstance(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } } //在service層須要這麼寫 CustomerDao customerDao = CustomerDaoFactory.getCustomerFactory().getCustomerDao();
service和dao層須要解耦,web層與service層也須要解耦,web
每一個解耦都須要構建一個工廠類。code
還有一種很基礎的實現方式:get
public Object getInstance(String clazz) { clazz = properties.getProperty(clazz); try { return Class.forName(clazz).newInstance(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } 在service層須要這麼寫: CustomerDao customerDao = (CustomerDao) BasicFactory.getBasicFactory().getInstance("CustomDao"); 不只須要將類名變成String參數傳進去,還須要強轉一下。
因此,就用第一個吧。io