是否可以重構(gòu)以下代碼以消除重復(fù)?我希望我的 GameObject 實(shí)現(xiàn)調(diào)用不同更新處理程序(如我的“AfterUpdate”)的“更新”任務(wù)的邏輯。當(dāng)前版本有效,但“更新”有兩種實(shí)現(xiàn),它們是相同的。在 GameObject 上調(diào)用的 AfterUpdate 應(yīng)該對其屬性進(jìn)行操作,在 HeroGameObject 上調(diào)用的 AfterUpdate 應(yīng)該可以訪問 HeroGameObject 的屬性(例如“health”)。我可以做什么更好?謝謝你。package mainimport "fmt"type Point struct { x, y int}///////////////////////type GameObject struct { Point title string status int ticks float32 spriteIndex int}func (g *GameObject) Update() { if g.ticks == 0 { g.spriteIndex++ g.AfterUpdate() }}func (g *GameObject) AfterUpdate() { g.status = 0 //suppose it does something meaningful fmt.Println("GameObject afterUpdate handler invoked")}///////////////////////type HeroGameObject struct { GameObject health float32}func (h *HeroGameObject) Update() { if h.ticks == 0 { h.spriteIndex++ h.AfterUpdate() }}func (h *HeroGameObject) AfterUpdate() { h.health-- //suppose it does something meaningful but *different*, using its own properties, for example "health" fmt.Println("HeroGameObject afterUpdate handler invoked")}///////////////////////func main() { gameObject := &GameObject{ Point: Point{ x: 0, y: 0, }, title: "dummy object", status: 0, ticks: 0, spriteIndex: 0, } heroObject := &HeroGameObject{ GameObject: GameObject{ Point: Point{ x: 0, y: 0, }, title: "hero object", status: 0, ticks: 0, spriteIndex: 0, }, health: 0, } gameObject.Update() heroObject.Update()}輸出:調(diào)用游戲?qū)ο?afterUpdate 處理程序調(diào)用 HeroGameObject afterUpdate 處理程序
1 回答

至尊寶的傳說
TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
像這樣使用標(biāo)志函數(shù)和基本接口怎么樣?
type BaseGameObject interface {
Ticks() int
IncSpriteIndex()
AfterUpdate()
}
func UpdateGameObject(o BaseGameObject) {
if o.Ticks() == 0 {
o.IncSpriteIndex()
o.AfterUpdate()
}
}
func (o *GameObject) Ticks() int {
return o.ticks
}
func (o *GameObject) IncSpriteIndex() {
o.spriteIndex++
}
- 1 回答
- 0 關(guān)注
- 153 瀏覽
添加回答
舉報(bào)
0/150
提交
取消