In the project im working on, people wrote services class to access DAO. Almost every business object has it\'s own service which use it\'s own DAO. On some services, we are usi
Yes, the "singleton pattern" along with lazy initialisation will do. Don't initialise services in the constructor, but in static getters:
class OrderService {
private static OrderService instance;
private OrderDAO orderDAO;
public OrderService() {
orderDAO = DAOFactory.getDAOFactory().getOrderDAO();
}
public static synchronized OrderService getInstance() {
if (instance == null) {
instance = new OrderService();
}
return instance;
}
}
As Jonathan stated, you can also inject services to other services, but that might not be needed. If synchronisation is prone to lead to a memory issue, you can resolve this using volatile
. See also this answer here, elaborating on the "double-checked locking pattern" (be careful though, to get this right!)