Question

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?

Was it helpful?

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;
    }
}

OTHER TIPS

Your buisness logic should definetly only handle DAO interfaces, that will hide actual imlementation.

To be able to quickly change implementing classes, take a look at IoC containers, such as Spring

sound like you want to use an interface, it is java's basic method of decoupling implementation from the desired behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top