Java Reference
In-Depth Information
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private InputStream getInputStream(String configLocation)
{
return Thread
.currentThread()
.getContextClassLoader()
.getResourceAsStream(configLocation);
}
C
Declares a simple
factory method
public static DaoFactory getInstance() {
return instance;
}
D
Gets a DAO
public Object getDao(Class daoInterface){
if (instanceMap.containsKey(daoInterface)) {
return instanceMap.get(daoInterface);
}
return createDao(daoInterface);
}
E
Makes sure we only
have one DAO per type
private synchronized Object createDao(
Class daoInterface
) {
Class implementationClass;
try {
implementationClass = Class.forName((String)
daoMap.get(daoInterface));
Object implementation =
implementationClass.newInstance();
instanceMap.put(implementationClass, implementation);
} catch (Exception e) {
throw new RuntimeException(e);
}
return instanceMap.get(daoInterface);
}
}
Clearly, this is not the greatest factory ever written, but it is pretty darn small and
efficient. Its public interface consists of only two methods: getInstance() and
getDao() . The private constructor loads the configuration file, which in this
case is just a properties file with name/value pairs for the interface and implemen-
tation names. This class is a self-contained singleton, so the getInstance()
method
b
C
D
just returns the one instance of the class. The getDao() method
Search WWH ::




Custom Search