【純血Golang】 通過組合嵌入實現代碼共用

來源:互聯網
上載者:User

標籤:

      應用開發中的一個常見情景,為了避免簡單重複,需要在基類中實現共用代碼,著同樣有助於後期維護。

如果在以往的支援類繼承的語言中,比如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】 通過組合嵌入實現代碼共用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.