Changing Implementation
A class that calls methods on a variable whose type is a DAO interface is not coupled with a specific DAO implementation class. * The class doesn't know which implementation class's methods it is calling; this is good.
In the future, we could change which DAO implementation we use, and thus where the class gets its data, by changing the object the interface variable refers to.
Drill¶
Previous versions of
StockServlethave used aStockProvider, and then used the data it provided.The new
StockServletuses a DAO. In this drill, we will change theStockServletto use a DAO that interacts with a database.
DAOPattern/
- Run the project on Eclipse's Server.
- Search for the Stock
aapl.
DAOPattern/com.example.daopattern.drills.servlets.StockServlet
StockServletuses anInMemoryStockDAOImplin itsinit()method. * OpenInMemoryStockDAOImplto see where it gets its data. *init()is called by the web container when it instantiates the servlet.public class StockServlet extends HttpServlet { private StockDAO stockDAO; @Override public void init() throws ServletException { stockDAO = new InMemoryStockDAOImpl(); } // ... }
- Change this to use a
JDBCStockDAOImplinstance.- Now search for different stocks, like
ZTSorPBI.- Note that you did not have to change any more servlet code because it uses the interface's methods.