Golang接口实现多态

package main
 
import (
    "fmt"
)
 
func main() {
    user := &User{name: "Chris"}
    user.ISubUser = &NormalUser{}
    user.sayHi()
    user.ISubUser = &ArtisticUser{}
    user.sayHi()
}
 
type ISubUser interface {
    sayType()
}
 
type User struct {
    name string
    ISubUser
}
 
func (u *User) sayHi() {
    u.sayName()
    u.sayType()
}
 
func (u *User) sayName() {
    fmt.Printf("I am %s.", u.name)
}
 
type NormalUser struct {
 
}
 
func (n *NormalUser) sayType() {
    fmt.Println("I am a normal user.")
}
 
type ArtisticUser struct {
 
}
 
func (a *ArtisticUser) sayType() {
    fmt.Println("I am an artistic user.")
}
//RUN 之后输出:
I am Chris.I am a normal user.
I am Chris.I am a artistic user.
//重用了sayName和sayHi方法,sayType方法可以多态来实现。
posted @ 2019-05-23 16:35  下哼哼  阅读(1575)  评论(0编辑  收藏  举报