Once we build these bases classes and interfaces. We may start implement it. First, is to implement the DAO interface. In my implementation, I create one more layer of abstraction before going in to the concrete implementation that is storage medium dependent.
So I create an interface that implement (with keyword extends) DAO interface, said CustomerDAO. My CustomerDAO are as below (Customer here is just a JavaBean):
public interface CustomerDAO extends DAO{Then I implement the CustomerDAO interface into concrete implementation CustomerMySqlDAO. This class provide implementation that is specific to MySQL database and of course it is optimize for MySQL since it is not meant to be generic across DBMS or other storage medium.
public Customer getCustomer (int id);
public void addCustomer (Customer customer);
public void updateCustomer (Customer customer);
public void deleteCustomer (Customer customer);
}
After DAO is build, I also build my DAOFactory implementor, CustomerDAOFactory. The getDAO( ) method are as follow:
public DAO getDAO() {Until here, everything is ready for DAO for Customer object. You can use them in your Java program easily. Here a simple example:
ReceipientDAO dao = new ReceipientMySqlDAO();
return dao;
}
public static void main(String args[]) throws DAOException{Since down-casting is dangerous (it may throws ClassCastException at run time), and also create overhead. I am still looking for an alternative to avoid down-casting in my DAO implementation. If you have any idea for this, just post it here to share with others.
DAOFactory daoFactory = DAOFactory.getInstance("CustomerDAOFactory");
CustomerDAO dao = (CustomerDAO) daoFactory.getDAO();
Customer c = dao.getCustomer(2); // get customer by ID
System.out.println("Customer Name: " + c.getName());
}
No comments:
Post a Comment