vendredi 28 mai 2021

Should I do DAO as Singleton when Implementing Abstract factory or there is a better appoach?

I have DaoFactory abstract class that return concrete Factory I have done it only to Mysql yet

public abstract class DAOFactory {
    public static final int MYSQL = 1;
    public abstract CarDao getCarDao();
    public abstract UserDao getUserDao();
    public abstract OrderDao getOrderDao();
    public abstract CarCategoryDao getCarCategoryDao();
    public static DAOFactory getDAOFactory(
            int whichFactory) {
        switch (whichFactory) {
            case MYSQL:
                return new MySQLDAOFactory();
            default :
                return null;
        }
    }
}

And I have MysqlFactory that return Dao implementation

public class MySQLDAOFactory extends DAOFactory {
    private static final Logger LOGGER = LogManager.getLogger(MySQLDAOFactory.class);
    private static DataSource DATA_SOURCE;

    public static void dataSourceInit(){
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:comp/env");
            DATA_SOURCE = (DataSource) envContext.lookup("jdbc/UsersDB");
        } catch (NamingException e) {
            LOGGER.error(e);
        }
    }
    public static Connection getConnection(){
        Connection connection = null;
       if(DATA_SOURCE==null){
         dataSourceInit();
       }
       try {
           connection = DATA_SOURCE.getConnection();
            } catch (SQLException e) {
                LOGGER.error(e);
            }
        return connection;
    }
    @Override
    public CarDao getCarDao() {
        return new MySQLCarDao();
    }
    @Override
    public UserDao getUserDao() {
        return new MySQLUserDao();
    }
    @Override
    public OrderDao getOrderDao() {
        return new MySQLOrderDao();
    }
    @Override
    public CarCategoryDao getCarCategoryDao() {
        return new MySQLCarCategoryDao();
    }
}

Do I need to make Dao singletons or is there a better approach?I took this implementation from oracle site

Aucun commentaire:

Enregistrer un commentaire