2011-08-17 40 views
1

我對如何最好地構造一個新類的接口有所懷疑。將有兩個其他班級與新班級PlatformSensor進行通信。新課程Pathfinder將從Sensor接收傳感器數據,並在計算路徑時考慮任何新數據。 Platform正在沿Pathfinder創建的路徑移動,但如果Sensor檢測到威脅,Pathfinder將生成一個新路徑,該路徑將在下一次嘗試移動時由Platform自動使用。類接口設計的難題

我現在已經勾勒出了該接口看起來像這樣的僞C++:

class Sensor { 
    Detect() { 
     // Get Data 
     Pathfinder.Process(Data) 
    } 
} 

class Platform { 
    Move() { 
     while(Can move further) 
      Waypoint w = Pathfinder.GetNextWaypoint() 
      // Move towards w 
      if(Arrived at w) 
       Pathfinder.PassedWaypoint() 
    } 
} 

class Pathfinder { 
    Process(Data) { 
     // Adapt path to accomodate Data 
     RecalculatePath() 
    } 
    GetNextWaypoint() { 
     if(!Path calculated) 
      RecalculatePath() 
     return Path.front() 
    } 
    PassedWaypoint() { 
     Path.pop_front() 
    } 
    RecalculatePath() { 
     // Do pathfinding 
    } 
    vector<Waypoint> Path 
} 

我不是很滿意,平臺將如何與探路者互動。另一方面,如果我讓平臺獲取整個路徑,它將不得不周期性地檢查是否有什麼變化,並且可能不夠經常,從而陷入任何檢測到的威脅。

該設計如何改進?

+0

探路者可以使用回調來通知Platform路由已經改變。這將最大限度地減少數據複製並使輪詢冗餘。 – RedX

+0

或者,稍微概括一下回調想法,使用消息。您是否正在使用可能已經內置消息傳遞的框架? –

回答

1

您可以使用設計模式"Observer"

然後,Platform對象可以訂閱Pathfinders事件「開始重新計算」(立即停止移動或返回或...)和「計算完成」。當Pathfinder對象有一個新路徑時,Platform對象可以一次請求整個數據。