More Requirements for the Case Study

In Chapter 18, “The Template Method Pattern,” I ignored the issue of how to instantiate the database object required by my current context. I may not want to make the Client responsible for instantiating the database object. Instead, I might want to give that responsibility to the QueryTemplate class itself.

In Chapter 18, each derivation of the QueryTemplate was specialized for a particular database. Thus, I might want to make each derivation responsible for instantiating the database to which it corresponds. This would be true whether the QueryTemplate (and its derivations) was the only class using the database or not. Figure 19-1 shows this solution.

Figure 19-1. The Template Method (doQuery) using the Factory Method pattern (makeDB).


In Figure 19-1, the doQuery method in the Template Method is using makeDB to instantiate the appropriate database object. QueryTemplate does not know which database object to instantiate; it only knows that one must be instantiated and provides an interface for its instantiation. The derived classes from QueryTemplate will be responsible for knowing which ones to instantiate. Therefore, at this level, I can defer the decisions on how to instantiate the database to a method in the derived class.

Since there is a method involved in making an object, this approach is called a Factory Method.

Public or protected methods?

Note that the makeDB methods are protected (as indicated by the # signs). In this case, only the QueryTemplate class and its derivations can access these methods. If I want objects other than QueryTemplate to be able to access these methods, then they should be public. This is another, quite common, way to use the Factory Method. In this case I still have a derived class making the decision as to which object to instantiate.


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

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