本文最后更新于一年前或更久前,其中的信息可能已经有所发展或是发生改变。
前言
Go的面向对象本身与传统的面向对象的概念差别就很大,比如之前一直在折磨我的不能继承,当然接口的奇怪定义也是让Go的面向对象之路很难走的原因之一,通过几篇网上博客的参考,打算彻底把这个地方给弄明白
非侵入式的接口
只有方法的接口
Go接口的明显的特点是:其本身只有函数实现,并没有内置变量预定义
根据1️⃣中给出的例子:
type Person interface {
GetAge() int
GetName() string
}
type Car interface { //Car接口
GetAge() int
GetName() string
}
type Student struct { //Student接口
age int
name string
}
func (s Student) GetAge() int {
return s.age
}
func (s Student) GetName() string {
return s.name
}
可以看到这段代码中预定义了Car
和Student
两个接口,它们具有相同的方法,如果我们在任意类中实现了这两个方法,则说明我们实现了这个接口:
func main() {
var p Person= Student{20, "Elon"}
fmt.Println("This person name is", p.GetName())
fmt.Println("This person age is", p.GetAge())
var c Car= Student{1, "BMW"}
fmt.Println("This car name is", c.GetName())
fmt.Println("This car age is", c.GetAge())
}
这样的接口定义带来的好处:
接口与类不再绑定出现:
可以先写类,然后再根据具体的需要进行接口的定义
为Go提供了一个类似于面向对象的接口约束
例子
我们一个大团队在开发一个商城系统,m端、app端、pc端都有购物车的需求,底层根据不同的需求已经实现了一个Cart类,通过该类可以获取购物车价格、数量等1️⃣。例如:
type Cart struct {
price float32
num int
}
func (c Cart) GetPrice() float32 {
return c.price
}
func (c Cart) GetNum() int {
return c.num
}
这个时候前端要进行调用了,他们可以自由定义接口名称用于接受,只需要关心自己的接口需要什么方法,Cart 是否全部实现了需要的方法,每一个端完全可以自己定义一个接口,接口名称、定义的方法顺序都可以不同。1️⃣
也就是说,可以根据需要为类设计不同的接口,比如有时候我们想让一些功能只能在APP中实现或者一些功能在APP中由于安全性更高,可以取消掉身份验证参数的传输
如:
//Web端
type WebCart interface{
GetInfo() string
Pay(token string) bool
DeleteItem() bool
}
//移动端
type MobileCart interface{
GetInfo() string
Pay(uuid uint64) bool //不再需要token
DeleteItem() bool
GetMobilePrice() float64 //移动端APP专属优惠
}
其中GetInfo()
和DeleteItem()
还可以使用同一个实现
Reference:
1️⃣ https://segmentfault.com/a/1190000013280677