1 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超2個贊
這似乎是一個關(guān)于如何設(shè)計(jì)項(xiàng)目中的數(shù)據(jù)結(jié)構(gòu)和操作及其依賴關(guān)系的一般軟件工程問題。
正如您所發(fā)現(xiàn)的,循環(huán)導(dǎo)入是不好的。有很多方法可以改變設(shè)計(jì)來解耦事物。一個是清晰的層——例如,Bank
應(yīng)該依賴Human
而不是相反。但是,如果您想提供方便的功能來將錢從 轉(zhuǎn)移Human
到Human
,您可以做的一件事是定義一個Bank
對象將實(shí)現(xiàn)的接口。
然而,為簡單起見,我建議嚴(yán)格分層。沒有真正的理由 aHuman
應(yīng)該依賴于 a?Bank
。在極限情況下,這可能會變得太麻煩,因?yàn)?code>Humans 需要更多服務(wù)(你會依賴Human
aBus
來讓Bus
es 移動Human
s 嗎?)
為了回答評論和更新的問題,我會保持簡單:
package main
import (
? ? "fmt"
? ? "log"
)
type Human struct {
? ? ID? ?int64
? ? Name string
}
type Account struct {
? ? ID int64
? ? // Note: floats aren't great for representing money as they can lose precision
? ? // in some cases. Keeping this for consistency with original.
? ? Cash float64
? ? DaysSinceActive int64
}
type Bank struct {
? ? Accounts map[int64]Account
}
// Not checking negatives, etc. Don't use this for real banking :-)
func (bank *Bank) Transfer(src int64, dest int64, sum float64) error {
? ? srcAcct, ok := bank.Accounts[src]
? ? if !ok {
? ? ? ? return fmt.Errorf("source account %d not found", src)
? ? }
? ? destAcct, ok := bank.Accounts[dest]
? ? if !ok {
? ? ? ? return fmt.Errorf("destination account %d not found", dest)
? ? }
? ? // bank.Accounts[src] fetches a copy of the struct, so we have to assign it
? ? // back after modifying it.
? ? srcAcct.Cash -= sum
? ? bank.Accounts[src] = srcAcct
? ? destAcct.Cash += sum
? ? bank.Accounts[dest] = destAcct
? ? return nil
}
func main() {
? ? gary := Human{19928, "Gary"}
? ? sam := Human{99555, "Sam"}
? ? bank := Bank{Accounts: map[int64]Account{}}
? ? bank.Accounts[gary.ID] = Account{gary.ID, 250.0, 10}
? ? bank.Accounts[sam.ID] = Account{sam.ID, 175.0, 5}
? ? fmt.Println("before transfer", bank)
? ? if err := bank.Transfer(gary.ID, sam.ID, 25.0); err != nil {
? ? ? ? log.Fatal(err)
? ? }
? ? fmt.Println("after transfer", bank)
}
這段代碼使用了松散耦合。銀行需要知道的關(guān)于一個人的所有信息就是他們的 ID(可以是 SSN 或根據(jù)姓名、出生日期和其他內(nèi)容計(jì)算出來的東西)來唯一地識別他們。人類應(yīng)該持有銀行(如果一個人在多家銀行都有賬戶怎么辦?)。銀行不應(yīng)該持有人(如果賬戶屬于多個人、公司、虛擬實(shí)體怎么辦?)等等。這里不需要接口,如果確實(shí)需要,您可以安全地將每種數(shù)據(jù)類型放在它們自己的包中。
- 1 回答
- 0 關(guān)注
- 163 瀏覽
添加回答
舉報