Skip to content

Commit 03143d5

Browse files
authored
Merge pull request #2 from sensorario/decorator
add new decorator pattern
2 parents 1d1268e + 6ea791d commit 03143d5

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

structural/decorator/README.md

+14-6
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,28 @@
11
# Decorator
22

3-
The decorator pattern provide a lot of benefits when working with legacy code. In this example I have a legacy code. For example a legacy recipe. A decorator add functionality. The functionality in this example is the method Decorate. In the real world Decorate() is represented by a method that must be decorate.
3+
The decorator pattern provide a lot of benefits when working with legacy code. In this example legacy code is represented by a legacy recipe. A decorator add functionality and in this example decorators are new ingredients.
44

55
```go
66
type LegacyRecipe struct {
7-
Decorate() (string, error)
87
}
8+
```
9+
Starting from legacy code, we must have a default behavior. For example LegacyRecipe could have a method called `Decorate` that provide the recipe.
910

11+
```go
1012
func (lr *LegacyRecipe) Decorate() (string, error) {
11-
return "Legacy recipe with the following ingredients:", nil
13+
return "Original behavior: ", nil
1214
}
1315
```
1416

15-
All object needed to implement the decorator pattern should implement same interface.
17+
All object needed to implement the decorator pattern should implement same interface. Because of we must improve the functionality of `Decorate` method we'll create an interface like this.
1618

1719
```go
1820
type Decorable interface {
1921
Decorate() (string, error)
2022
}
2123
```
2224

23-
Because of we are treating with a legacy recipe. All new ingredient must contains a `Decorable` recipe.
25+
And because of we are treating with a legacy recipe, all new ingredient must implement a `Decorable` interface.
2426

2527
```go
2628
type NewIngredient struct {
@@ -35,6 +37,12 @@ func (ni *NewIngredient) Decorate() (string, error) {
3537
if err != nil {
3638
return "", err
3739
}
38-
return fmt.Sprintf("%s %s,", s, "new ingredient"), nil
40+
return fmt.Sprintf("%s %s,", s, "with decoration"), nil
3941
}
4042
```
43+
As you can see we can use this decorator with:
44+
45+
```go
46+
dec := &NewIngredient{&LegacyRecipe{}}
47+
dev.Decorate() // Original behavior: with decoration
48+
```

0 commit comments

Comments
 (0)