-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathadapter.go
66 lines (52 loc) · 1.16 KB
/
adapter.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
/*!
* \brief. Adapter. Convert the interface of a class into
* another interface clients expect.Adapter lets classes
* work together that couldn't otherwise because of
* incompatible interfaces.
*/
package main
import "fmt"
// The target interface.
type Target interface {
Request()
}
// The interface that needs to be adapted.
type IAdaptee interface {
SpecificRequest()
}
// Adaptee.
type Adaptee struct{}
func (*Adaptee) SpecificRequest() {
fmt.Printf("Adaptee::SpecificRequest().\n")
}
// Adapter.
type ObjectAdapter struct {
adaptee IAdaptee
}
func NewObjectAdapter(adaptee IAdaptee) Target {
return &ObjectAdapter{
adaptee: adaptee,
}
}
func (oa *ObjectAdapter) Request() {
oa.adaptee.SpecificRequest()
}
// Adapter v2.
type ObjectAdapter2 struct {
IAdaptee
}
func (oa *ObjectAdapter2) Request() {
oa.IAdaptee.SpecificRequest()
}
func main() {
// Only function SpecificRequest() can be called,
// but all you need is function Request().
adaptee := &Adaptee{}
adaptee.SpecificRequest()
// You call Request() now.
adapter := NewObjectAdapter(adaptee)
adapter.Request()
// v2
adapter2 := &ObjectAdapter{adaptee}
adapter2.Request()
}