Skip to content

Commit 0776427

Browse files
committed
Added the Template Method Pattern.
1 parent 5b2ae1d commit 0776427

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

authors.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ The following people are totally rad and awesome because they have contributed r
2121
* Frederic Hemberger
2222
* Mike Hatfield *[email protected]*
2323
* [Anton Rissanen](http://github.com/antris) *[email protected]*
24+
* Calum Robertson *http://github.com/randusr836*
2425
* ...You! What are you waiting for? Check out the [contributing](/contributing) section and get cracking!
2526

2627
# Developers
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
---
2+
layout: recipe
3+
title: Template Method Pattern
4+
chapter: Design Patterns
5+
---
6+
## Problem
7+
8+
You need to execute a series of steps according to some algorithm or recipe and wish to provide the implementation for any of the steps.
9+
10+
## Solution
11+
12+
Use the Template Method to describe each step in a superclass, delegating the implementation of each step to a subclass.
13+
14+
For example, imagine you wish to model various types of document and each one may contain a header and a body.
15+
16+
{% highlight coffeescript %}
17+
class Document
18+
produceDocument: ->
19+
@produceHeader()
20+
@produceBody()
21+
22+
produceHeader: ->
23+
produceBody: ->
24+
25+
class DocWithHeader extends Document
26+
produceHeader: ->
27+
console.log "Producing header for DocWithHeader"
28+
29+
produceBody: ->
30+
console.log "Producing body for DocWithHeader"
31+
32+
class DocWithoutHeader extends Document
33+
produceBody: ->
34+
console.log "Producing body for DocWithoutHeader"
35+
36+
doc1 = new DocWithHeader
37+
doc1.produceDocument()
38+
39+
doc2 = new DocWithoutHeader
40+
doc2.produceDocument()
41+
{% endhighlight %}
42+
43+
## Discussion
44+
45+
In this example, there are two steps, one for producing a document header and the second for producing the document body; these two steps are given empty implementations in the superclass. The DocWithHeader implements both the body and header steps, whereas the DocWithoutHeader only impements the body step.

0 commit comments

Comments
 (0)