From now on I explain how to use the Factory pattern to implement the DAO pattern:
- a good idea is to start creating an interface containing the methods that we want implement in our daos, like the following one:
- public interface GenericDAO {
- public void save(Object object) throws DAOException;
- public void update(Object object) throws DAOException;
- public void remove(Object object) throws DAOException;
- public Object findByPrimaryKey(Object pk) throws DAOException;
- public Collection findAll() throws DAOException;
- }
- and if we want we can extend the java.lang.Exception to implement our specific exception (DAOException)
- public class DAOException extends Exception {
- public DAOException(String message) {
- super(message);
- }
- public DAOException(Throwable e) {
- super(e);
- }
- }
- Then we need to implement the core class which implements the factory and singleton patterns: in this manner we will use use always only one instance of our DAO (singleton pattern); while the factory pattern returns an interface, in this case the GenericDAO, that at run time will be a real class that implements that interface. Then we create a properties file which will be sued by the DAOFactory to discover the real implementations for DAOs that will be requested at run time by the application.
- public class DAOFactory {
- private static DAOFactory factory = null;
- private Properties props = null;
- private DAOFactory() {
- try {
- props = new Properties();
- props.load(DAOFactory.class.getResourceAsStream("daos.properties"));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static DAOFactory getInstance() {
- if (factory == null) {
- factory = new DAOFactory();
- }
- return factory;
- }
- public GenericDAO getDAO(String name) {
- GenericDAO dao = null;
- try {
- dao = (GenericDAO) Class.forName(props.getProperty(name))
- .newInstance();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- return dao;
- }
- }
Nessun commento:
Posta un commento