案例:
假设现在需要一个车辆管理系统,其中包括不同类型的车辆,例如汽车、摩托车、自行车等,并且需要能够对这些车辆进行管理,例如计算它们的运行费用、打印车辆信息等。
为实现这个功能,可以使用 Go 的接口编程实现多态。首先,定义一个车辆接口:
// 定义车辆接口
type Vehicle interface {
Run() float64 // 计算车辆行驶费用
PrintInfo() // 打印车辆信息
}
然后,为每种车辆类型定义一个结构体,并实现 Vehicle 接口中的方法:
// 定义汽车结构体
type Car struct {
Brand string // 汽车品牌
Distance float64 // 行驶里程
}
// 实现车辆接口的 Run 方法
func (c *Car) Run() float64 {
return c.Distance * 0.8 // 假设汽车每公里费用为 0.8 元
}
// 实现车辆接口的 PrintInfo 方法
func (c *Car) PrintInfo() {
fmt.Printf("汽车品牌:%s,行驶里程:%v 公里\n", c.Brand, c.Distance)
}
// 定义摩托车结构体
type Motorcycle struct {
Brand string // 摩托车品牌
Distance float64 // 行驶里程
}
// 实现车辆接口的 Run 方法
func (m *Motorcycle) Run() float64 {
return m.Distance * 0.5 // 假设摩托车每公里费用为 0.5 元
}
// 实现车辆接口的 PrintInfo 方法
func (m *Motorcycle) PrintInfo() {
fmt.Printf("摩托车品牌:%s,行驶里程:%v 公里\n", m.Brand, m.Distance)
}
// 定义自行车结构体
type Bicycle struct {
Brand string // 自行车品牌
PedalTimes int // 踏板数
Distance float64 // 行驶里程
}
// 实现车辆接口的 Run 方法
func (b *Bicycle) Run() float64 {
return 0 // 自行车不产生运行费用,返回 0
}
// 实现车辆接口的 PrintInfo 方法
func (b *Bicycle) PrintInfo() {
fmt.Printf("自行车品牌:%s,踏板次数:%v,行驶里程:%v 公里\n", b.Brand, b.PedalTimes, b.Distance)
}
现在可以定义一个管理器,对不同类型的车辆进行管理,例如计算它们的运行费用和打印车辆信息:
// 定义车辆管理器
type VehicleManager struct {
Vehicles []Vehicle // 车辆集合
}
// 计算车辆运行费用
func (vm *VehicleManager) CalcCost() float64 {
var totalCost float64
for _, vehicle := range vm.Vehicles {
totalCost += vehicle.Run()
}
return totalCost
}
// 打印车辆信息
func (vm *VehicleManager) PrintInfo() {
for _, vehicle := range vm.Vehicles {
vehicle.PrintInfo()
}
}
可以创建不同类型的车辆对象并添加到管理器中进行管理:
// 创建不同类型的车辆对象
car := &Car{Brand: "奔驰", Distance: 500}
motorcycle := &Motorcycle{Brand: "宝马", Distance: 300}
bicycle := &Bicycle{Brand: "凤凰", PedalTimes: 1000, Distance: 50}
// 创建车辆管理器并添加车辆对象
vm := &VehicleManager{
Vehicles: []Vehicle{car, motorcycle, bicycle},
}
// 计算车辆运行费用,并打印车辆信息
cost := vm.CalcCost()
fmt.Printf("车辆总费用:%v 元\n", cost)
vm.PrintInfo()
通过使用 Go 的接口编程实现多态,可以方便地管理不同类型的车辆,并灵活地进行功能扩展。