Chapter 4: Template Method

Head First Design Patterns puts the template method in a chapter titled Encapsulating Algorithms. The idea is that if you have a group of similar classes that tend to perform the same steps in the same order, you can abstract out a superclass that has the methods those classes needs, and each subclass can override those methods to perform the tasks they need to do. In addition, the object in charge of executing the algorithm takes care of calling the templated methods.

As mentioned in the previous post, NSView is a frequently encountered example of this pattern, having a drawRect: method that your subclass implements to take care of drawing itself. The programmer doesn’t need to know the details of how or when drawRect: will be called, or even what kind of medium it is drawing to.

This chapter doesn’t have any example programs: it’s a discussion of where Cocoa uses the Template Method and the advantages and disadvantages of using templates in new designs.

Cocoa’s archiving and unarchiving techniques, covered in Chapter 11, make extensive use of the Template Method. The NSView and NSResponder classes are commonly encountered examples of this pattern in Cocoa programming.

Xcode’s implementation file templates (!) are helpful because they often include stubs of the methods that you need to override.

The main negative issue with the Template Method is that it involves subclassing, and subclassing produces the tightest possible coupling between classes, which is usually a bad idea.

Advertisements
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

One Response to Chapter 4: Template Method

  1. Erica says:

    NSarchiver ftw

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s