Go語言基礎(十三)—— Go面向物件簡單小練習
阿新 • • 發佈:2018-11-25
練習要求:
介面->父類實現->多種子類實現->多型
-
定義介面IPerson,定義吃喝睡三個抽象方法;
-
定義一個IPerson的實現類Person,實現吃喝睡方法;
-
定義IWorker勞動者介面,擁有勞動方法Work()(output string)其中output是其工作產出,和休息方法Rest();
-
IWorker實現三個不同職業的子類:程式設計師Coder、老師Teacher、農民Farmer,並建立一個Worker的集合;
-
實現週一到週五全體工作,如果是週六日程式設計師工作其他人休息;
案例實現:
package main import "fmt" //定義IPerson介面 type IPerson interface { Eat(); Drink(); Sleep(); } //定義Person結構體 type Person struct { name string } //Person實現介面的Eat方法 func (pp *Person) Eat() { fmt.Println("我是Person,這是我的eat方法") } //Person實現介面的Drink方法 func (pp *Person) Drink() { fmt.Println("我是Person,這是我的Drink方法") } //Person實現介面的Sleep方法 func (pp *Person) Sleep() { fmt.Println("我是Person,這是我的Sleep方法") } //定義IWorker介面 type IWorker interface { Work() (output string); Rest() } //coder實現類 type Coder struct { Person } //Coder實現IWorker的Work方法 func (coder *Coder) Work() (output string) { fmt.Println("I am Coder,this is my Work method!") return "程式碼" } //Coder實現Rest方法 func (coder *Coder) Rest() { fmt.Println("I am Coder,this is my Rest method!") } //teacher實現類 type Teacher struct { Person } //Teacher實現work方法 func (teacher *Teacher) Work() (output string) { fmt.Println("I am teacher ,this my Work method !") return "students" } //Teacher實現Rest方法 func (teacher *Teacher) Rest() { fmt.Println("I am teacher ,this my Rest method !") } //farmer 實現類 type Farmer struct { Person } //Farmer實現work方法 func (farmer *Farmer) Work() (output string) { fmt.Println("I am Farmer,this is my work method !") return "foods" } //Farmer實現Rest方法 func (farmer *Farmer) Rest() { fmt.Println("I am Farmer,this is my Rest method !") } func main() { //宣告結構體 var coder Coder var teacher Teacher var farmer Farmer coder.name = "wek" teacher.name = "wrr" farmer.name = "WEK" //宣告IWorker介面方面統一管理 worker := make([]IWorker, 0) worker = append(worker, &coder) worker = append(worker, &teacher) worker = append(worker, &farmer) //如果是工作日,則所有人工作 fmt.Println("今天是工作日") for _, workers := range worker { workers.Work() } //如果是休息日,則只有coder工作,其餘人休息 fmt.Println("今天是休息日") for _, workers := range worker { if _, ok := workers.(*Coder); ok { workers.Work() } else { workers.Rest() } } }
結果為: