Atul
Atul

Reputation: 1774

Service and DAO Design pattern

I have doubt with Delegate-Service and DAO design pattens. Our team thought we will use Singleton patterns for DAOFactory and DAO Objects. DAOFactory will contain all the available DAOs as its attribute and will provide them whenever required.

Now we are having one doubt whether Service say e.g. AuthenticateSerivce shall contain all the required DAO say e.g. UserDAO, RoleDAO etc as attributes? or It should call get**DAO() whenever its need on demand basis and not set as its own attribute.(Attached is java file)

Code Snippet:

public class AuthenticateService {
    UserDao userDao;
    RoleDao roleDao;

    public AuthenticateService(){
        DaoFactory daoFactory = DaoFactory.getInstance();
        userDao = daoFactory.getUserDao();
        roleDao = daoFactory.getRoleDao();
    }


}


public class DaoFactory {

    private static DaoFactory instance = null;

    UserDao userDao;
    RoleDao roleDao;
    AnnualScheduleDao annualScheduleDao;
    WeeklyScheduleDao weeklyScheduleDao;
    ProgramSlotDao programSlotDao;

    private DaoFactory (){
        // Authenticate
        userDao = new UserDaoImpl();
        roleDao = new RoleDaoImpl();

        // Schedule
        annualScheduleDao = new AnnualScheduleDaoImpl();
        weeklyScheduleDao = new WeeklyScheduleDaoImpl();
        programSlotDao = new ProgramSlotDaoImpl();

    }


}

Which approach is better and in which situations?

Upvotes: 2

Views: 1858

Answers (1)

Kenston Choi
Kenston Choi

Reputation: 2942

I think the first one is better (i.e., attributes), because it's easier to manage them. The code is going to be cleaner as well, rather than having calls to the Factory in different methods, or having a dao variable in each method. You can easily modify the Daos to use later on, without having to replace in several areas. If you decide to initialize the Dao there, or to create a custom dao to use, or to use dependency injection later on, then you don't have to revisit all calls to the DaoFactory.

The second issue is on the use of singletons for DAO. I'm not sure how each DaoImpl is being done, but there's a chance of having thread issues when the service is accessed by more than one thread (again, it depends on how you implement your Daos) and they are sharing the same Dao. Or maybe you want to use a Factory that instantiates a new Dao for every request? But if that's the case, then I'm sure you will go for the first option, since you wouldn't want to recreate a dao in each method.

Daos are likely cheap to create (assuming that your team is worrying on performance issues) so they do not need to be instantiated on-demand, but you should do some connection or resource pooling (e.g., reusing Db connections).

Upvotes: 1

Related Questions