亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go中如何正確使用組合

Go中如何正確使用組合

Go
qq_遁去的一_1 2023-05-15 15:43:52
我是新來的;有兩個共享相似行為的文件,并被告知使用組合來避免重復代碼,但不能完全理解組合的概念。這兩個文件具有共同的功能,但又各有不同。播放器1.gopackage gametype confPlayer1 interface {    Set(string, int) bool    Move(string) bool    Initialize() bool}func Play(conf confPlayer1) string {    // code for Player1}// ... other funcs播放器2.gopackage gametype confPlayer2 interface {    Set(string, int) bool    Move(string) bool    // Initializer is only for Player1}func Play(conf confPlayer2) string {    // code for Player2, not the same as Player1.}// ... the same other funcs from player1.go file// ... they differ slighly from player1.go funcs有沒有辦法將所有內容合并到一個player.go文件中?
查看完整描述

1 回答

?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

Golang 使用組合。

  1. 對象組合:使用對象組合代替繼承(在大多數傳統語言中使用)。對象組合意味著一個對象包含另一個對象(比如對象 X)的對象,并將對象 X 的職責委托給它。這里不是覆蓋函數(如在繼承中),而是將函數調用委托給內部對象。

  2. 接口組合:在接口組合中,接口可以組合其他接口,并使在內部接口中聲明的所有方法集成為該接口的一部分。

現在具體回答你的問題,你這里說的是界面組成。您還可以在此處查看代碼片段:https ://play.golang.org/p/fn_mXP6XxmS

檢查以下代碼:

播放器2.go

package game


type confPlayer2 interface {

    Set(string, int) bool

    Move(string) bool

    }


func Play(conf confPlayer2) string {

    // code for Player2, not the same as Player1.

}

播放器1.go


package game


type confPlayer1 interface {

    confPlayer2

    Initialize() bool

}


func Play(conf confPlayer1) string {

    // code for Player1

}

在上面的代碼片段中,confPlayer1接口中包含了接口confPlayer2,除了Initialize函數只是confPlayer1的一部分。


現在你可以為播放器 2 使用接口 confPlayer2,為播放器 1 使用 confPlayer1。請參閱下面的代碼片段:


播放器.go


package game


type Player struct{

  Name string

  ...........

  ...........

}



func (p Player) Set(){

  .......

  .......

}


func (p Player) Move(){

  ........

  ........

}



func Play(confPlayer2 player){

   player.Move()

   player.Set()

}


查看完整回答
反對 回復 2023-05-15
  • 1 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號