Search code examples
javainterfaceimplementationdecouple

java hide implementing class details between two layers


I am building an application that has a business logic layer which needs to access the DAO layer for all DB related stuff. My requirement is such that the DAOImpl class can keep changing so I am looking for ways in which I can get a handle to the DAOImpl class in my business logic class without the need to know the actual DAOImpl class. Is there any way I can achieve this in Java?


Solution

  • DAOImpl class should implement an interface DAOLayer (say). You businessLogic class should be composed of a DAOLayer object.

    class BusinessLogic
    {
        /// ...
    
        DAOLayer daoLayer;
    
        public BusinessLogic(DAOLayer daoLayer)
        {
            this.daoLayer = daoLayer;
        }
    
        /// ...
    }
    
    class DAOImpl implements DAOLayer
    {
        /// ...
    }
    

    You should pass the actual implementation of DAOLayer while creating BusinessLogic class object.

    Similar to following:

    DAOLayer aDaoLayer = new DAOImpl();
    BusinessLogic bl = new BusinessLogic(aDaoLayer);
    

    OR

        public BusinessLogic()
        {
            this.daoLayer = DAOFactory.create(true);
        }
    
    class DAOFactory
    {
        public static DAOLayer create(bool isDB)
        {
            DAOLayer aDao;
    
            if(isDB)
            {
                aDao = // create for DB
            }
            else
            {
                aDao = // create for file
            }
    
            return aDao;
        }
    }