Go语言接口类型(interface)

Go语言的接口类型(interface)

在Go语言中、如果一个类型实现了一个接口的所有方法,那么这个类型的实例就可以存储在这个接口类型的实例中「鸭子类型」

Go语言不是一个「面向对象」的编程语言、使用「interface」实现类似面向对象的、继承、封装、多态、编程的思想;

接口的使用
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
package main

import "fmt"

// 接口抽象
type Card interface {
Display()
}

type Memory interface {
Storage()
}

type CPU interface {
Calculate()
}

type Computer struct {
cpu CPU
memory Memory
card Card
}

// 工厂函数
func NewComputer(cpu CPU, memory Memory, card Card) *Computer {
return &Computer{
cpu: cpu,
memory: memory,
card: card,
}
}

func (c *Computer) DoWork() {
c.cpu.Calculate()
c.memory.Storage()
c.card.Display()
}

// 实现接口部分
type IntelCPU struct {
CPU
}

func (i *IntelCPU) Calculate() {
fmt.Println("001-->IntelCPU 实现 CPU接口的 Calculate()方法....")
}

type IntelMemory struct {
Memory
}

func (i *IntelMemory) Storage() {
fmt.Println("002-->IntelMemory 实现 Memory接口的 Storage()方法....")
}

type IntelCard struct {
Card
}

func (i *IntelCard) Display() {
fmt.Println("003-->IntelCard 实现 Card接口的 Display()方法....")
}

func main() {
// 业务逻辑
computer := NewComputer(&IntelCPU{}, &IntelMemory{}, &IntelCard{})
computer.DoWork()
}
1
2
3
001-->IntelCPU 实现 CPU接口的 Calculate()方法....
002-->IntelMemory 实现 Memory接口的 Storage()方法....
003-->IntelCard 实现 Card接口的 Display()方法....