Golang继承多态实现

思路:
1.结构体方法可以继承(也不是继承,父结构体的方法可以顺延下来)。
2.利用接口。
3.利用父结构体self变量,替换为真实使用的对象,调用的时候使用struct.self.Method调用接口中的方法。

func TestPolymorphic(t *testing.T) {
	child := &Child{Parent: &Parent{}}
	child.self = child
	child.TestSay()
}

type ISay interface {
	Say()
}
type Parent struct {
	self ISay
}

func (p *Parent) TestSay() {
	p.self.Say()
}
func (p *Parent) Say() {
	fmt.Println("say A")
}

type Child struct {
	*Parent
}

猜你喜欢

转载自uzoice.iteye.com/blog/2358287