package main
import "fmt"
type User struct {
Name string
Email string
Notifier userNotifier
}
func (u *User)notifier(message string) error {
return u.Notifier.sendMessage(u, message)
}
type userNotifier interface {
sendMessage(u *User, message string) error
}
type emailNotifier struct {}
func (e emailNotifier)sendMessage(u *User, message string) error {
_, err := fmt.Printf("send email to %s with content %s\n", u.Name, message)
return err
}
type smsNotifier struct {}
func (s smsNotifier) sendMessage(u *User, message string) error {
_, err := fmt.Printf("send sms to %s with content %s\n", u.Name, message)
return err
}
func main() {
user1 := User{
Name: "sss",
Email: "sss@qq.com",
Notifier: emailNotifier{},
}
user2 := User{
Name: "xxx",
Email: "xxx@qq.com",
Notifier: smsNotifier{},
}
user1.notifier("hello")
user2.notifier("world")
}
基于接口实现Go多态
未经允许不得转载:IDEA激活码 » 基于接口实现Go多态