Go: 多态

Go语言借助接口实现多态。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

package main

import "fmt"

type Income interface {
calculate() int
source() string
}

type FixedBilling struct {
projectName string
biddedAmount int
}

type TimeAndMaterial struct {
projectName string
noOfHours int
hourlyRate int
}

func (fb FixedBilling) calculate() int {
return fb.biddedAmount
}

func (fb FixedBilling) source() string {
return fb.projectName
}

func (tm TimeAndMaterial) calculate() int {
return tm.noOfHours * tm.hourlyRate
}

func (tm TimeAndMaterial) source() string {
return tm.projectName
}

type Advertisement struct {
adName string
CPC int
noOfClicks int
}

func (a Advertisement) calculate() int {
return a.CPC * a.noOfClicks
}

func (a Advertisement) source() string {
return a.adName
}


func calculateNetIncome(ic []Income) {
var netincome int = 0
for _, income := range ic {
fmt.Printf("Income From %s = $%d\n", income.source(), income.calculate())
netincome += income.calculate()
}
fmt.Printf("Net income of organisation = $%d", netincome)
}

func main() {
project1 := FixedBilling{projectName: "Project 1", biddedAmount: 5000}
project2 := FixedBilling{projectName: "Project 2", biddedAmount: 10000}
project3 := TimeAndMaterial{projectName: "Project 3", noOfHours: 160, hourlyRate: 25}
bannerAd := Advertisement{adName: "Banner Ad", CPC: 2, noOfClicks: 500}
popupAd := Advertisement{adName: "Popup Ad", CPC: 5, noOfClicks: 750}
incomeStreams := []Income{project1, project2, project3, bannerAd, popupAd}
calculateNetIncome(incomeStreams)
}
文章目录
  1. 1. 使用接口实现多态
|