Applying the Template Method to the Case Study

In this case study, the variations in database access occur in the particular implementations of the steps involved. Figure 18-1 illustrates this.

Figure 18-1. Using the Template Method pattern to perform a query.


I have created a method called doQuery that handles the query I need to perform. I pass in the name of the database and the query specification. The doQuery method follows the five general steps above, providing virtual methods for the steps (such as formatConnect and formatSelect) that must be implemented differently.

The doQuery method is implemented as follows. As shown in Figure 18-1, it first needs to format the CONNECT command required to connect to the database. Although the abstract class (QueryTemplate) knows this format needs to take place, it doesn't know how to do this. The exact formatting code is supplied by the derived classes. This is true for formatting the SELECT command as well.

The Template Method manages to do this because the method call is made via a reference pointing to one of the derived classes. That is, although QueryControl has a reference of type QueryTemplate, it is actually referring to an OracleQT or an SQLSvrQT object. Thus, when the doQuery method is called on either of these objects, the methods resolved will first look for methods of the appropriate derived class. Let's say our QueryControl is referring to an OracleQT object. Since OracleQT does not override QueryTemplate, the QueryTemplate's doQuery method is invoked. This starts executing until it calls the formatConnect method. Since the OracleQT object was requested to perform doQuery, the OracleOT's formatConnect method is called. After this, control is returned to the QueryTemplate's doQuery method. The code common to all queries is now executed until the next variation is needed—the formatSelect method. Again, this method is located in the object that QueryControl is referring to (OracleQT in this example).

When a new database is encountered, the Template Method provides us with a boilerplate (or template) to fill out. We create a new derived class and implement the specific steps required for the new database in it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.202.240