forked from alex-leonhardt/go-decorator-pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
56 lines (43 loc) · 1.32 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"fmt"
"log"
"os"
)
// Echoer is a interface that consists of a single method "Echo". Echo is a method that may return an error or nil.
type Echoer interface {
Echo() error
Dump() string
}
// a custom struct data type
type text struct {
s string
}
// Here we have a method Echo() that implements the 1st part of the Echoer interface, the implementation is implicit
func (t text) Echo() error {
_, err := fmt.Println(t.s)
return err
}
// Here we have a method Dump() that implements the 2nd part of the Echoer interface, the implementation is implicit and now complete
func (t text) Dump() string {
return fmt.Sprintf(t.s)
}
func printIt(e Echoer) {
e.Echo()
}
func dumpIt(e Echoer) string {
return e.Dump()
}
// Decorates the Echoer interface.
func loggingDecorator(e Echoer, l *log.Logger) Echoer {
l.Println(">>>", dumpIt(e))
return e
}
func main() {
myLogger := log.New(os.Stdout, "### ", 3)
t := text{s: "happy halloween"}
// not decorated, sends t, which has method Echo, which implements Echoer
printIt(t)
tD := loggingDecorator(t, myLogger) // with the dumpIt function, or calleing e.Dump() we can access the value of the struct and output it as a log
tD.Echo() // not in the "log" as the execution of Echo() happened after the interface was already executed
}