What is DAO factory pattern?

扶醉桌前 提交于 2019-11-29 19:33:27
Adrian E. Labastida Cañizares

Probably what you don't understand is how the code works? It seems fine.

Just FYI:

  • What is defined as UserDAOImpl can be better understood if you consider naming it as UserDAOMySQLImpl and another new one as UserDAOMSSQLImpl, and so on for each database access you may need.

  • In each of those you should handle the connections and add other things like private functions for that specific database server configuration it may need and not forcibly needed to be declared in the interface (UserDAO) but as minimum you must always implement all the methods defined in the interface, then in the Factory (UserDAOFactory) conditions you could have something like this:

`

public class UserDAOFactory{

    public static UserDAO getUserDAO(String type){ 
        if (type.equalsIgnoreCase("mysql")){
            return new UserDAOMySQLImpl();
        }else{
            return new UserDAOMSSQLImpl();
        }
    }
}

A little clearer?

Then, in the client side instead of a hardcoded line like:

UserDAO userDAO=UserDAOFactory.getUserDAO("jdbc");

You could have a properties file to be able to switch between DAOs dynamically, having retrieved that string from the properties file you can simply do:

UserDAO userDAO=UserDAOFactory.getUserDAO(myStringFromPropertiesFile);

myStringFromPropertiesFile would contain "mysql" or "mssql" according to the definition in your properties file.

Hope this helps!

DAO stands for "Data Access Object". It's an interface-based class that handles all your CRUD operations with a relational database for a particular object. Here's an example that uses generics:

package persistence;

public interface GenericDao<K extends Serializable, T> 
{
    public T find(K id);
    public List<T> find();
    public K save(T value);
    public void update(T value);
    public void delete(T value);
}

Think of a factory as a "virtual constructor": its creation method returns an interface type, but you can ask it to create any number of different implementations as needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!