Search code examples
javadesign-patternsdaofactory-pattern

DAOFactory: return a new instance or always the same?


a simple question that came to my mind: I have my DAOFactory class:

public class DAOFactory {
    public static UserDAO createUserDAO() {
        return new UserDAO();
    }

    public static AdminDAO createUserDAO() {
        return new AdminDAO();
    }
    //etc etc
}

Doing this way (which AFAIK is standard), every time someone requests a DAO, a new instance is created. Actually, there's no need to have more than one instance for each DAO, unless I'm missing something. :D

So, why don't we do like this?

public class DAOFactory {
    /* eventually we could use lazy initialization */
    private static UserDAO userDAO = new UserDAO();
    private static UserDAO AdminDAO = new AdminDAO();
    //etc etc
    public static UserDAO createUserDAO() {
        return userDAO;
    }

    public static AdminDAO createUserDAO() {
        return adminDAO;
    }
    //etc etc
}

What are the differences between the former and the latter, speaking in terms of performance and memory? I guess that practically speaking, there are no difference between these two implementations for the clients of DAOFactory.


Solution

  • Basically if your DAO classes are immutable, or stateless then you can do it, but if they are not, you must make the DAO classes thread safe, if multiple threads acces the same object and mess with its state, it can create failures.

    (In a single threaded environment, what you wrote is acceptable, but when you're writing DAO pattern, I'm sure it's not single threaded)

    So why we don't do it, why isn't it the same: thread safety becomes a concern.