在 Go 语言中,是通过接口来实现的多态。

这里以商品接口来写一段代码演示一下。

先定义一个商品(Good)的接口,意思是一个类型或者结构体,只要实现了settleAccount() 和 orderInfo() 两个方法,那这个类型/结构体就是一个商品。

type Good interface {
    settleAccount() int
    orderInfo() string
}
然后我们定义两个结构体,分别是手机和赠品。

type Phone struct {
    name string
    quantity int
    price int
}

type FreeGift struct {
    name string
    quantity int
    price int
}
然后分别为他们实现 Good 接口的两个方法

// Phone
func (phone Phone) settleAccount() int {
    return phone.quantity * phone.price
}
func (phone Phone) orderInfo() string{
    return "您要购买" + strconv.Itoa(phone.quantity)+ "个" +
        phone.name + "计:" + strconv.Itoa(phone.settleAccount()) + "元"
}

// FreeGift
func (gift FreeGift) settleAccount() int {
    return 0
}
func (gift FreeGift) orderInfo() string{
    return "您要购买" + strconv.Itoa(gift.quantity)+ "个" +
        gift.name + "计:" + strconv.Itoa(gift.settleAccount()) + "元"
}
实现了 Good 接口要求的两个方法后,手机和赠品在Go语言看来就都是商品(Good)类型了。

这时候,我挑选了两件商品(实例化),分别是手机和耳机(赠品,不要钱)

iPhone := Phone{
    name:     "iPhone",
    quantity: 1,
    price:    8000,
}
earphones := FreeGift{
    name:     "耳机",
    quantity: 1,
    price:    200,
}
然后创建一个购物车(也就是类型为 Good的切片),来存放这些商品。

goods := []Good{iPhone, earphones}
最后,定义一个方法来计算购物车里的订单金额

package main

import (
	"fmt"
	"strconv"
)

// 定义一个接口
type Good interface {
	settleAccount() int
	orderInfo() string
}

type Phone struct {
	name string
	quantity int
	price int
}

func (phone Phone) settleAccount() int {
	return phone.quantity * phone.price
}
func (phone Phone) orderInfo() string{
	return "您要购买" + strconv.Itoa(phone.quantity)+ "个" +
		phone.name + "计:" + strconv.Itoa(phone.settleAccount()) + "元"
}

type FreeGift struct {
	name string
	quantity int
	price int
}

func (gift FreeGift) settleAccount() int {
	return 0
}
func (gift FreeGift) orderInfo() string{
	return "您要购买" + strconv.Itoa(gift.quantity)+ "个" +
		gift.name + "计:" + strconv.Itoa(gift.settleAccount()) + "元"
}

func calculateAllPrice(goods []Good) int {
	var allPrice int
	for _,good := range goods{
		fmt.Println(good.orderInfo())
		allPrice += good.settleAccount()
	}
	return allPrice
}
func main()  {
	iPhone := Phone{
		name:     "iPhone",
		quantity: 2,
		price:    8000,
	}
	earphones := FreeGift{
		name:     "耳机",
		quantity: 3,
		price:    200,
	}

	goods := []Good{iPhone, earphones}
	allPrice := calculateAllPrice(goods)
	fmt.Printf("该订单总共需要支付 %d 元", allPrice)
}