Java Reference
In-Depth Information
removing the dependency on the implementation, we have just added a depen-
dency on the interface.
What we mean is that if you have an interface for your DAO and an implemen-
tation for it, how do you use the implementation? If you are not using a factory,
you are likely doing it this way:
AccountDao accountDao = new AccountDaoImpl();
See the problem? While we have separated our DAO and its implementation, we
are still referring to each of them in a single place. This is not adding much value,
unless you pass the DAO all over your application. A better pattern would be to
use something like this:
AccountDao accountDao =
(AccountDao)DaoFactory.get(AccountDao.class);
In that example, what is the implementation? We neither know nor care, because
the DaoFactory handles it for us. All we care about is that this DaoFactory item
returns an object that implements the AccountDao interface. We do not care if it
uses LDAP , JDBC , or smoke and mirrors to make it happen, as long as it does.
Creating an abstract factory is fun and easy! OK , maybe not fun, but still easy.
In this section, we build a simple one, and talk about why you would want to use
one for your DAO classes.
So, what does this DaoFactory look like under the hood? Surprisingly, it is just a
few dozen lines of code, as listing 11.7 shows.
Listing 11.7
A super simple DAO factory
public class DaoFactory {
private static DaoFactory instance = new DaoFactory();
private final String defaultConfigLocation =
"DaoFactory.properties";
private Properties daoMap;
private Properties instanceMap;
private String configLocation = System.getProperty(
"dao.factory.config",
defaultConfigLocation
);
B
Declares a Private
constructor—it's a singleton
private DaoFactory(){
daoMap = new Properties();
instanceMap = new Properties();
try {
daoMap.load(getInputStream(configLocation));
Search WWH ::




Custom Search