標籤:
應用開發中的一個常見情景,為了避免簡單重複,需要在基類中實現共用代碼,著同樣有助於後期維護。
如果在以往的支援類繼承的語言中,比如c++,Java,c#等,這很簡單!可是go不支援繼承,只能mixin嵌入,且看下面的代碼:
type ManKind interface{ Say(s string); GetMouth()string}type Man struct{ ManKind }func NewMan() ManKind{ return &Man{};}func (this *Man)GetMouth()string{ return "M0"}func (this *Man) Say(s string){ fmt.Printf("\n Speak with mouth[%s] : \"%s\"",this.GetMouth(),s);}type StrongMan struct{ Man}func NewStrongMan()ManKind{ return &StrongMan{}}func (this*StrongMan)GetMouth()string{ return "M1"}func main(){ NewMan().Say("good luck!") NewStrongMan().Say("good luck!")}
如果支援繼承,很明顯應該輸出
Speak with mouth[M0] : "good luck!" Speak with mouth[M1] : "good luck!"
但是在golang中只能輸出:
Speak with mouth[M0] : "good luck!" Speak with mouth[M0] : "good luck!"
StrongMan中調用Say(),此時可以將指標傳遞到內嵌類,只是簡單的指向了Man的方法,在ManKind中調用GetMouth就是ManKind自己的GetMouth,和StrongMan沒有關係。
當然,我們可以在StrongMan中覆蓋Say方法
func (this *StrongMan)Say(s string){ fmt.Printf("\n Speak with mouth[%s] : \"%s\"",this.GetMouth(),s);}
此時,當然可以正確輸出,因為本來調用的就都是StrongMan自己的方法了,這又和我們的初衷相違背了。那麼這種情況怎麼實現呢?我的方法是,讓Man再髒一點兒,把需要的東西傳遞給組合進來的類。
給Man增加一個屬性mouth,增加一個SetMouth方法,修改一下GetMouth方法,StrongMan的GetMouth方法刪除掉,再修改一下NewStrongMan方法,最後的代碼如下:
package mainimport( "fmt")type ManKind interface{ Say(s string); SetMouth(m string) GetMouth()string}type Man struct{ ManKind mouth string}func NewMan() ManKind{ return &Man{mouth:"M0"};}func (this *Man)GetMouth()string{ return this.mouth;}func (this *Man)SetMouth(s string){ this.mouth=s;}func (this *Man) Say(s string){ fmt.Printf("\n Speak with mouth[%s] : \"%s\"",this.GetMouth(),s);}type StrongMan struct{ Man}func NewStrongMan()ManKind{ sm := &StrongMan{}
sm.SetMouth("M1");
return sm;} func main(){ NewMan().Say("good luck!") &NewStrongMan().Say("good luck!")}
當然,如果你不願意用Get、Set方法,也可以直接輸出Man的Mouth屬性。
【純血Golang】 通過組合嵌入實現代碼共用