简体   繁体   中英

Example of DAO Factory whose datasource is not going to change across the different versions

Here is the diagram which represents the structure of DAO Factory whose dataStorage is not going to be changed across the different versions:

在此处输入图片说明

My question is about the example of an implementation. Assume we have two different DAO s

UserDAO

public interface UserDAO{
    //CRUD operations and something else
}

PaymentsDAO

public interface PaymentsDAO{
    //CRUD operations and something else  
}

Now we have two Implementations of the DAO s:

UserDAOImpl

public interface UserDAOImpl{
    DataSource dataSource;
    //Implementation of the operations
}

PaymentsDAOImpl

public interface PaymentsDAOImpl{
    DataSource dataSource;
    //Implementation of the operations
}

Now we're creating a new class, called DAOFactory :

public abstract class DAOFactory{
    UserDAO userDAO;
    PaymentsDAO paymentsDAO;

    public abstract getUserDAO();
    public abstract getPaymentDAO();
}

So, now if we have a BusinessObject, say PaymentService, we just add a DAOFactory as a field and use it right? But why do we ever need to incapsulate all DAO 's into a factory? Wouldn't it be more simple if we jsut added neccessary DAO -objects as properties into the BusinessObject ?

Using dependency injection, your service has minimal coupling and no knowledge of the dao factory.

    DaoFactory daoFactory = new RdbDaoFactory(dataSource);

    myPaymentService.setUserDao(daoFactory.getUserDAO());
    myPaymentService.setPaymentDao(daoFactory.getPaymentDAO());

Encapsulating all the dao's into a factory gives you a central point for instantiating them, and is easily switched in future if your persistence layer changes.

Your last point about isn't it better to use Dao's in the business object (rather than factories) is correct, and I hope my example illustrates this for you.

By encapsulating all of the DAOs in a separate factory you are allowing your BusinessObject to not worry about the DAOs.

Let's assume one DAO is a hammer.

Let's assume the other DAO is a screwdriver.

Let's assume your BusinessObject is a carpenter who builds tables.

Your carpenter doesn't need to know anything how the hammer or the screwdriver is made or what materials were used to manufacture them, at some points he just needs the

thatOneThingWhichScrewsTheScrewsIn()

or

thatOtherThingWhichCanBeUsedToDriveNailsIn()

When he needs those, he knows a guy.

This guy will hook him up with exactly what he needs.

This guy is the tool guy.

This guy is the DAO factory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM