类接口设计困难

时间:2011-08-17 10:47:53

标签: c++ class-design

我对如何最好地构建新类的接口有疑问。将有另外两个类与新类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
}

我对平台与探路者的互动方式并不满意。另一方面,如果我让平台获取整个路径,它将不得不定期检查某些事情是否发生了变化,并且可能不够频繁,从而进入任何检测到的威胁。

如何改进此设计?

1 个答案:

答案 0 :(得分:1)

您可以使用设计模式"Observer"

然后,Platform对象可以订阅Pathfinders事件“Started recalculation”(立即停止移动或返回或......)和“Calculation finished”。当Pathfinder对象中有新路径时,Platform对象可以立即请求整个数据。