• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 894
  • Last Modified:

why use daoFactory

In  our java web application  we are   using  this method for getting an instanse of a Dao Class by passing the name of the class as parameter string to this method and this method  returns an object which we cast  to spacific Dao Class.

 public BaseDAO getDAO(String sDaoClass)
        BaseDAO dao = null;
            dao = (BaseDAO)Class.forName(sDaoClass).newInstance();
        catch(ClassNotFoundException clsEx)
        catch(InstantiationException initEx)
        catch(IllegalAccessException iaEx)
        return dao;

Now i want to know why this pattern is used to get the instanse of the class.

we can also get the object of a class by calling the constructor :
                    specificDaoClass  referenceName = new  specificDaoClass ();
then why we use this(getDAO(String)) to get instanse of classes.

what is the difference between these two approach,
is there any drawbacks ,limitations or benifits while using these approaches
i mean i m totally confused about these approaches
please give ur comments,share ur knowldge,  not just  google reference.
please help
Thanks in Advance
2 Solutions
not a lot.
using getDao() would not require the dao classes to be available at compile time, thats about the only difference.
Mayank SAssociate Director - Product EngineeringCommented:

Wanna a know a problem. Say you do not want to package all the class files in your ear/war/jar(maybe you donot use it but you do use it somewhere in some other ear/jar/war) or maynot even want to compile them.

Now you have a common DAO, with the (BaseDAO)Class.forName(sDaoClass).newInstance() approach your code works but with new specificDaoClass () the code bombs.

I am sure whoever used such a code must have had a very bad time with some existing code, to use this approach. When you look at the bigger picture it would help.

Tommy BraasCommented:
One big advantage with the approach above is that a new version of a DAO can be subsituted in without ever needing to change, or recompile any code. This is especially true if the DAO declarations are interfaces. Compare to JDBC drivers for instance. You can replace a driver for a database by replacing the jar which contains the driver. No need to recompile any code.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Tackle projects and never again get stuck behind a technical roadblock.
Join Now