-1

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?

user2185805
  • 255
  • 4
  • 17
  • Just to add to the question, at any given point of time, there will just be one DAOImpl class that would be used. – user2185805 Mar 19 '13 at 09:58

3 Answers3

3

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;
    }
}
Azodious
  • 13,752
  • 1
  • 36
  • 71
  • I got this but how will the BusinessLogic constructor get a handle to the DAOImpl object. I would have to put in something like - this.daoLayer = new DAOImpl(); That will make specific to the current DAOImpl implementation. – user2185805 Mar 19 '13 at 10:01
  • see the edits. Within `BusinessLogic` DAO related objects should not be created. OR you can also use factory pattern. – Azodious Mar 19 '13 at 10:09
1

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

Nikita Skvortsov
  • 4,768
  • 24
  • 37
0

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

yurib
  • 8,043
  • 3
  • 30
  • 55