Skip to content

Commit b47a5bf

Browse files
committed
Merge branch 'template' of github.com:sensorario/go-design-patterns into template
2 parents 40984af + 0e26f1f commit b47a5bf

File tree

1 file changed

+53
-20
lines changed

1 file changed

+53
-20
lines changed

behavioral/template/README.md

Lines changed: 53 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,64 @@
22

33
## Description
44

5-
Strategy pattern consists in different way to solve same problem. In Strategy
6-
entire algorithm is store in different classes. In Template pattern the
7-
algorithm is just one. The template define steps but some steps are deferred to
8-
user.
5+
Strategy pattern consists in a different way to solve same problem with
6+
different strategies. In Strategy entire algorithm is store in different
7+
classes. In Template pattern, instead, the algorithm is just one. The template
8+
defines steps but some other steps are deferred to user.
99

10-
This kind of pattern is widely used in MVC web frameworks when steps are always
11-
the same:
10+
## Implementation
1211

13-
- Handle Request
14-
- Authentication
15-
- Authorization
16-
- Retrieve data from DB
17-
- Do something
18-
- Send Response
12+
In this case the template is a sort of flow of steps to solve a problem. While
13+
in strategy pattern each strategy implements entire solution, in this case the
14+
template define the steps execution but defer one or more steps to the user. In
15+
this case, the deferred step is called `templateSteps`.
1916

20-
All these steps are execute for each http request. Just the `do something`
21-
part is defined by the user.
17+
```go
18+
type TheTemplate interface {
19+
first() string
20+
second() string
21+
templateSteps(MessageRetriever) string
22+
}
23+
```
2224

23-
## Implementation
25+
The `MessageRetriever` is an interface with `Message()` method. The template
26+
pattern here will joins strings. While first and third steps are implemented,
27+
the custom step is implemented by user.
28+
29+
```go
30+
type MessageRetriever interface {
31+
Message() string
32+
}
33+
```
34+
35+
Now let's implement a concrete `Template`.
36+
37+
```go
38+
type Template struct{}
39+
```
40+
41+
In this case first and second steps are defined. The `templateSteps` will join
42+
different strings receiving the third step from outside.
43+
44+
```go
45+
func (t *Template) first() string {
46+
return "hello"
47+
}
48+
49+
func (t *Template) second() string {
50+
return "template"
51+
}
52+
```
2453

2554
```go
26-
type TranslatorRing interface {
27-
Next(TranslatorRing)
28-
GetNext() TranslatorRing
29-
KnowsWord(s string) bool
30-
TranslationOf(s string) string
55+
func (t *Template) templateSteps(m MessageRetriever) string {
56+
return strings.Join(
57+
[]string{
58+
t.first(),
59+
m.Message(),
60+
t.second(),
61+
},
62+
" ",
63+
)
3164
}
3265
```

0 commit comments

Comments
 (0)