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 using references to other services. At the moment, people are instantiating needed services inside the constructor.
But now, I have trouble because service A needs service B and service B needs service A so a call to either constructor results in stack overflow ...
Example (pseudo-code) :
//Constructor of OrderService
public OrderService() {
orderDAO = DAOFactory.getDAOFactory().getOrderDAO();
itemService = new ItemService();
}
//Constructor of ItemService
public ItemService() {
itemDAO = DAOFactory.getDAOFactory().getItemDAO();
orderService = new OrderService();
}
How would you solve this ? using singleton pattern ?
Thanks
The Spring Framework solves this problem by using dependency injection. In short, what it does is to instantiate all the DAOs, and then set the dao-dependencies after instantiation, but before main business logic.
If you have to do this manually, here's an example:
/*
OrderService
*/
public OrderService ()
{
orderDAO = DAOFactory.getDAOFactory().getOrderDAO();
}
public setItemService (ItemService service)
{
itemService = service;
}
/*
ItemService
*/
public ItemService ()
{
itemDAO = DAOFactory.getDAOFactory().getItemDAO();
}
public setOrderService (OrderService service)
{
orderService = service;
}
/*
Bring it together in some other class
*/
...
// instantiate singletons
orderService = new OrderService ();
itemService = new ItemService ();
// inject dependencies
orderService.setItemService (itemService);
itemService.setOrderService (orderService);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With