Java - Business Service, data access objects - Should Singletons be used or not?
Consider a web application with business layer and data access layer. So, every request has to be passed through these two layers in order to get processed.
Since there would be frequent requests coming in, it is not wise to create a new business and data access objects to process each and every request. In this case, usually I tend 开发者_运维百科to go for Singletons of business and DAO.
But I hear lot of problems in using Singleton pattern, as many suggest against the pattern (mainly because its global). In that case, what would be the correct design strategy for the scenario I described above?
Service Objects should be Singleton.
You can use Spring to maintain singleton service objects for you.
The usual strategy used in such cases is to write the business services and data access objects not as singletons but as simple POJOs. And then use a container to manage the scope of the classes. Some examples of containers are Spring and Guice. You can even write your own container if your requirements are simple.
This way you get the benefits of the singleton pattern without its disadvantages (difficult to mock and test, etc).
A simple example:
public class PersonService {
public Person getPerson(String id) {
//find and return the person
}
}
public class PersonServiceSingletonFactory {
private PersonService service = new PersonService();
PersonService getInstance() {
return service;
}
}
I don't think that writing singletons on Servlet is good idea, you can create your business logic on ServletContextListener it will assure that only one instance of object will be run in container and it is thread-safe. you can access it the way @abhin4v explained. Unless you are using Spring framework this is what you need to do.
Hope it helps.
精彩评论