我正在學習 Go,并想知道在某些情況下,在 Golang 中根據消費者代碼將如何處理該結構來創建多個interface變體是否被認為是好的/好的/典型的(鼓勵?)實踐?struct我對此表示懷疑,因為我有一個結構對象,可以說它在我的代碼庫中做了太多事情,并且我想添加一些測試并僅模擬該結構的某些用法/使用者。說我有,對于(人為的)示例,環境結構// Environment/env.gopackage envtype Environment struct { sunny bool, fullMoon bool, temp float64 // ...}func (e *Environment) IsSunny() bool { return e.sunny}func (e *Environment) IsFullMoon() bool { return e.fullMoon}func (e *Environment) GetTemp() float64 { return e.temp}上面的結構體具有與一些環境條件(白天和夜間)相關的屬性和方法。然后這個結構有多個消費者,但每個消費者interface只關心可用方法的子集:// daytime.gotype DayEnv interface { IsSunny() bool GetTemp() float64}func getDaytime(de DayEnv) { sunStatus := getSunStatus(de) temp := getDayTemp(de) fmt.Printf("Today is %s and temperature is %s", sunStatus, temp)}// func getSunStatus(de DayEnv) string {}// func getDayTemp(de DayEnv) string {}// nightTime.gotype NightEnv interface { IsFullMoon() bool GetTemp() float64}func getNighttime(ne NightEnv) { moonPhase := getMoonPhase(ne) temp := getNightTemp(ne) fmt.Printf("Tonight the moon is %s and temperature is %s", moonPhase, temp)}// func getMoonPhase(ne NightEnv) string { }// func getNightTemp(ne NightEnv) string { }在我看來,雖然創建一個只關心結構方法子集的新接口使事情變得更加靈活,但擁有如此多(部分)接口重復并根據需要或在任何地方散布它們也感覺相當懶惰或錯誤他們被消耗了。我意識到這個例子有點做作,但是在更大的范圍內(就像很多很多消費者),或者也許一個文件具有x相同結構的接口......這種方法有什么問題嗎?
- 2 回答
- 0 關注
- 135 瀏覽
添加回答
舉報
0/150
提交
取消