23.07.2012 Views

Design Patterns Explained

Design Patterns Explained

Design Patterns Explained

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

286 Part V • Handling Variations with <strong>Design</strong> <strong>Patterns</strong><br />

Template Method<br />

using Factory<br />

Method<br />

Figure 19-1 The Template Method (doQuery) using the Factory<br />

Method pattern (makeDB).<br />

In Figure 19-1, the doQuery method in the Template Method is<br />

using makeDB to instantiate the appropriate database object.<br />

Query-Template does not know which database object to instantiate;<br />

it only knows that one must be instantiated and provides an interface<br />

for its instantiation. The derived classes from Query-Template will<br />

be responsible for knowing which ones to instantiate. Therefore, at<br />

this level, I can defer the decisions on how to instantiate the database<br />

to a method in the derived class.<br />

Since there is a method involved in making an object, this approach is<br />

called a Factory Method.<br />

Public or protected methods?<br />

Note that the makeDB methods are protected (as indicated by the #<br />

signs). In this case, only the QueryTemplate class and its derivations<br />

can access these methods. If I want objects other than<br />

QueryTemplate to be able to access these methods, then they<br />

should be public. This is another, quite common, way to use the<br />

Factory Method. In this case I still have a derived class making<br />

the decision as to which object to instantiate.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!