DAO Singleton – Should a DAO Be Singleton or Not?

daodesigndesign-patternsjavasingleton

I am developing a RESTful API and I think it is convenient to use DAOs for my resources because although I plan on just using memory to store them, I don't want to close a door to whoever is using my library if they decided to use a database implementation for the DAO.

My question is whether the DAO should be a singleton or not. If it is not, the service will have an instance of the DAO and it would look roughly like this:

@Path("eventscheduler")
public class EventSchedulerService {
    private IEventSchedulerDao dao = new EventSchedulerDao();

    // in case a different implementation is to be used
    public void setEventSchedulerDao(IEventSchedulerDao dao) {
        this.dao = dao;
    }

    @Path("{uniqueName}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Tournament getTournament(@PathParam("name") String uniqueName) {
        return dao.get(uniqueName);
    }

    @Path("create")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Tournament createTournament(Tournament tournament) {
        return dao.create(tournament);
    }
}

While if the DAO was a singleton, but I guess there wouldn't be much of a difference, just in the first line:

private IEventSchedulerDao dao = EventSchedulerDao.getInstance();

I would still have to use an IEventSchedulerDao instance, but I guess all singletons work like this right? For some reason I always correlate singletons to static methods, so instead of having a singleton instance visible to the user with getInstance(), this would be hidden and he/she would just use EventSchedulerDao.get(name), etc… in a static fashion. Is this a thing or is this just me?

So, should I or should I not have singleton DAOs?

And as a side question, is it alright my approach to have open doors for the user to implement their own DAOs?

Best Answer

I wouldn't use a singleton. It's a recognised anti-pattern, and makes testing difficult. I would much rather inject in a concrete implementation, and have your service reference a DAO interface (allowing you to inject different implementations in)

Related Topic