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.

Answers


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.


Need Your Help

Chrome Extensions: Background Script Catch Network and HTTP Errors

javascript google-chrome http google-chrome-extension error-handling

I'm developing a small Chrome extension for personal use on a very specific case (website automation) but I've a problem. How can I catch a network error on a background script and call a certain

Working out price of product using math in PHP

php math

If I have an integer value of 8.32 which represents the price of 100,000, what PHP function would I use if I wanted to work out the price of 3,268,937

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.