Skip to content

Commit d90a201

Browse files
committed
Add decorator pattern
1 parent c0937dd commit d90a201

File tree

3 files changed

+42
-25
lines changed

3 files changed

+42
-25
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ __Structural Patterns__:
2828
| [Adapter](adapter.go) | Adapts otherwise incompatible interfaces to work together by adapting one to the other |
2929
| [Bridge](bridge.go) | Decouples an interface from its implementation so that the two can vary independently |
3030
| [Composite](composite.go) | Encapsulates and provides access to a number of different objects |
31-
| [Decorator](decorator.go) | Adds behavior to an object, statically or dynamically |
31+
| [Decorator](structural/decorator.md) | Adds behavior to an object, statically or dynamically |
3232
| [Facade](facade.go) | Uses one class as an API to a number of others |
3333
| [Flyweight](flyweight.go) | Reuses existing instances of objects with similar/identical state to minimize resource usage |
3434
| [Model View Controller](mvc.go) | Divides an app into three interconnected parts to separate internal representation from presentation to user |

decorator.go

-24
This file was deleted.

structural/decorator.md

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Decorator Pattern
2+
Decorator structural pattern allows extending the function of an existing object dynamically without altering its internals.
3+
4+
Decorators provide a flexible method to extend functionality of objects.
5+
6+
## Implementation
7+
`LogDecorate` decorates a function with the signature `func(int) int` that
8+
manipulates integers and adds input/output logging capabilities.
9+
10+
```go
11+
type Object func(int) int
12+
13+
func LogDecorate(fn Object) Object {
14+
return func(n int) int {
15+
log.Println("Starting the execution with the integer", n)
16+
17+
result := fn(n)
18+
19+
log.Println("Execution is completed with the result", result)
20+
21+
return result
22+
}
23+
}
24+
```
25+
26+
## Usage
27+
```go
28+
func Double(n int) int {
29+
return n * 2
30+
}
31+
32+
f := LogDecorate(Double)
33+
34+
f(5)
35+
// Starting execution with the integer 5
36+
// Execution is completed with the result 10
37+
```
38+
39+
## Rules of Thumb
40+
- Unlike Adapter pattern, the object to be decorated is obtained by **injection**.
41+
- Decorators should not alter the interface of an object.

0 commit comments

Comments
 (0)