是否可以重構以下代碼以消除重復?我希望我的 GameObject 實現調用不同更新處理程序(如我的“AfterUpdate”)的“更新”任務的邏輯。當前版本有效,但“更新”有兩種實現,它們是相同的。在 GameObject 上調用的 AfterUpdate 應該對其屬性進行操作,在 HeroGameObject 上調用的 AfterUpdate 應該可以訪問 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()}輸出:調用游戲對象 afterUpdate 處理程序調用 HeroGameObject afterUpdate 處理程序
1 回答

至尊寶的傳說
TA貢獻1789條經驗 獲得超10個贊
像這樣使用標志函數和基本接口怎么樣?
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 關注
- 155 瀏覽
添加回答
舉報
0/150
提交
取消