Java circular references

前端 未结 4 1375
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 02:01

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

4条回答
  •  轮回少年
    2021-01-21 03:02

    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!)

提交回复
热议问题