1 回答

TA貢獻1821條經驗 獲得超5個贊
Golang 使用組合。
對象組合:使用對象組合代替繼承(在大多數傳統語言中使用)。對象組合意味著一個對象包含另一個對象(比如對象 X)的對象,并將對象 X 的職責委托給它。這里不是覆蓋函數(如在繼承中),而是將函數調用委托給內部對象。
接口組合:在接口組合中,接口可以組合其他接口,并使在內部接口中聲明的所有方法集成為該接口的一部分。
現在具體回答你的問題,你這里說的是界面組成。您還可以在此處查看代碼片段: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()
}
- 1 回答
- 0 關注
- 142 瀏覽
添加回答
舉報