亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

消除方法的重復

消除方法的重復

Go
翻閱古今 2021-09-10 10:14:51
是否可以重構以下代碼以消除重復?我希望我的 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++

}


查看完整回答
反對 回復 2021-09-10
  • 1 回答
  • 0 關注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號