如何用interface模拟多态
package main
import "fmt"
func main() {
var b *Base = new(Child).Create().GetBase()
b.Foo() // Sub.Foo is called
}
type IMatch interface {
Create() IMatch
GetBase() *Base
Foo()
}
type Base struct {
internal IMatch
}
type Child struct {
Base
}
// abstract
func (this *Base) Create() IMatch {
panic("Base.Create() should not be called")
return this
}
func (this *Base) GetBase() *Base {
return this
}
func (this *Base) Foo() {
if this.internal != nil {
this.internal.Foo()
}
}
func (this *Child) Create() IMatch {
this.internal = this
return this
}
func (this *Child) Foo() {
fmt.Println("Child.Foo is called")
}
Last updated