-
Notifications
You must be signed in to change notification settings - Fork 21
/
main.go
64 lines (55 loc) · 1.33 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
57
58
59
60
61
62
63
64
package main
import "fmt"
// 更好的方法
/*
方法三:
嵌套+将具体的实现Country和City私有化,不对外暴露实现细节
*/
// 内嵌struct :embedded 的特性来删除冗余的代码。当然,代价是初始化会稍微麻烦点
//type WithName struct {
// Name string
//}
type WithTypeName struct {
Type string // 多一个tYpe字段,代表是Country还是City,还可以其他
Name string
}
// 打印名字
type Country struct {
// Name string
// WithName //嵌套简化
WithTypeName
}
type City struct {
// Name string
// WithName //嵌套简化
WithTypeName
}
type Printer interface {
PrintStr()
}
// 给单独的WithName绑定方法
//func (w WithName) PrintStr() {
// fmt.Println(w.Name)
//}
func (c WithTypeName) PrintStr() {
fmt.Printf("%s:%s\n", c.Type, c.Name)
}
// 内部初始化复杂,返回接口类型
func NewCountry(name string) Printer {
return Country{WithTypeName{Type: "Country", Name: name}}
}
func NewCity(name string) Printer {
return City{WithTypeName{Type: "City", Name: name}}
}
func main() {
// 外部初始化要求简单
//c1 := Country{WithName{"China"}} // 初始化复杂
//c2 := City{WithName{"Shanghai"}} // 初始化复杂
// 初始化简单
c1 := NewCountry("China")
c2 := NewCity("Shanghai")
var cList = []Printer{c1, c2}
for _, v := range cList {
v.PrintStr()
}
}