-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathDecorator.go
90 lines (60 loc) · 1.43 KB
/
Decorator.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package pattern
import (
"strings"
"fmt"
"log"
)
//
// 装饰模式
// 动态地给一个对象添加一些额外的职责,同时又不改变其结构
//
// 接口
type MessageBuilder interface{
Build(messages ... string) string
}
// 基本信息构造器
type BaseMessageBuilder struct {
}
func(b *BaseMessageBuilder)Build(messages ... string) string{
return strings.Join(messages,",")
}
// 引号装饰器
type QuoteMessageBuilderDecorator struct {
Builder MessageBuilder
}
func(q *QuoteMessageBuilderDecorator)Build(messages ... string) string{
return "\""+q.Builder.Build(messages...)+"\""
}
// 大括号装饰器
type BraceMessageBuilderDecorator struct {
Builder MessageBuilder
}
func(b *BraceMessageBuilderDecorator)Build(messages ... string) string{
return "{"+b.Builder.Build(messages...)+"}"
}
// 或者
type Object func(int) int
func LogDecorate(fn Object) Object {
return func(n int) int {
log.Println("Starting the execution with the integer", n)
result := fn(n)
log.Println("Execution is completed with the result", result)
return result
}
}
func Double(n int) int {
return n * 2
}
// 调试
func DecoratorTest(){
var MB MessageBuilder
MB=&BaseMessageBuilder{}
fmt.Println(MB.Build("hello world"))
MB=&QuoteMessageBuilderDecorator{MB}
fmt.Println(MB.Build("hello world"))
MB=&BraceMessageBuilderDecorator{MB}
fmt.Println(MB.Build("hello world"))
//
f := LogDecorate(Double)
f(5)
}