File tree 3 files changed +42
-25
lines changed
3 files changed +42
-25
lines changed Original file line number Diff line number Diff line change @@ -28,7 +28,7 @@ __Structural Patterns__:
28
28
| [ Adapter] ( adapter.go ) | Adapts otherwise incompatible interfaces to work together by adapting one to the other |
29
29
| [ Bridge] ( bridge.go ) | Decouples an interface from its implementation so that the two can vary independently |
30
30
| [ 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 |
32
32
| [ Facade] ( facade.go ) | Uses one class as an API to a number of others |
33
33
| [ Flyweight] ( flyweight.go ) | Reuses existing instances of objects with similar/identical state to minimize resource usage |
34
34
| [ Model View Controller] ( mvc.go ) | Divides an app into three interconnected parts to separate internal representation from presentation to user |
Load Diff This file was deleted.
Original file line number Diff line number Diff line change
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.
You can’t perform that action at this time.
0 commit comments