golang继承与多态的一个例子

yanglikai · · 2394 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

package main

//继承
import (
    "fmt"
)

//人类接口
type Human interface{
	OneDay()
	Work() *Remuneration 
}

//报酬
type Remuneration struct{
	//钱
	Money int
	//食物
	Food  string
	//爵 位
	Title string
}

//人类
type People struct{
}  

func (s *People) Eat(){  
    println("people eat foot")  
}  

func (s *People) Drink(){  
    println("people drink water")  
}


////某一天的活动,继承人类接口
//func (s *People) OneDay(){  
//    s.Eat()
//    s.Drink()
//}

//富人
type RichPerson struct{  
    People  
    Age  uint32 
}  
//穷人
type PoorPerson struct{  
    People  
    Age  uint32 
}  
//贵族
type NoblePerson struct{  
    People  
    Age  uint32 
}  

func (s *RichPerson) Drink(){
    println("WangWu drink Orange Juice")  
}  
func (s *NoblePerson) Drink(){
    println("WangWu drink wine")  
}

func (s *People) Work() *Remuneration {  
    return &Remuneration{100,"",""}
}
    
func (s *PoorPerson) Work() *Remuneration {  
    return &Remuneration{0,"bread",""} 
}
    
func (s *NoblePerson) Work() *Remuneration {  
    return &Remuneration{1000,"","may be"}
}

////某一天的活动,继承人类接口
//func (s *People) OneDay() {  
//    s.Eat()
//    s.Drink()
//    
//    println(fmt.Sprintf("%#v", s.Work()))
//}

//富人RichPerson实现了human接口
func (s *RichPerson) OneDay() {  
    s.Eat()
    s.Drink()
    
    println(fmt.Sprintf("%#v", s.Work()))
}

//穷人PoorPerson实现了human接口
func (s *PoorPerson) OneDay() {  
    s.Eat()
    s.Drink()
    println(fmt.Sprintf("%#v", s.Work()))
}

//贵族RichPerson实现了human接口
func (s *NoblePerson) OneDay() {  
    s.Eat()
    s.Drink()
    println(fmt.Sprintf("%#v", s.Work()))
}

func main() {  
    zhangSan := PoorPerson{Age:25}
    liSi := RichPerson{Age:26}
    wangWu := NoblePerson{Age:27}
    
    zhangSan.OneDay()
    liSi.OneDay()
    wangWu.OneDay()
    
    println("----------上面的结果和下面的结果一样------------")
    
    var h1 Human = &zhangSan
    var h2 Human = &liSi
    var h3 Human = &wangWu
    
    polymorphism(h1)
    polymorphism(h2)
    polymorphism(h3)
}

//多态
func polymorphism(s Human) {
	s.OneDay()
}

运行结果:

people eat foot
people drink water
&main.Remuneration{Money:0, Food:"bread", Title:""}
people eat foot
WangWu drink Orange Juice
&main.Remuneration{Money:100, Food:"", Title:""}
people eat foot
WangWu drink wine
&main.Remuneration{Money:1000, Food:"", Title:"may be"}
----------上面的结果和下面的结果一样------------
people eat foot
people drink water
&main.Remuneration{Money:0, Food:"bread", Title:""}
people eat foot
WangWu drink Orange Juice
&main.Remuneration{Money:100, Food:"", Title:""}
people eat foot
WangWu drink wine
&main.Remuneration{Money:1000, Food:"", Title:"may be"}

 


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2394 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传